home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_descr.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  85.3 KB  |  3,107 lines

  1. # Test enhancements related to descriptors and new-style classes
  2.  
  3. from test_support import verify, vereq, verbose, TestFailed, TESTFN
  4. from copy import deepcopy
  5. import warnings
  6.  
  7. warnings.filterwarnings("ignore",
  8.          r'complex divmod\(\), // and % are deprecated$',
  9.          DeprecationWarning, r'(<string>|test_descr)$')
  10.  
  11. def veris(a, b):
  12.     if a is not b:
  13.         raise TestFailed, "%r is %r" % (a, b)
  14.  
  15. def testunop(a, res, expr="len(a)", meth="__len__"):
  16.     if verbose: print "checking", expr
  17.     dict = {'a': a}
  18.     vereq(eval(expr, dict), res)
  19.     t = type(a)
  20.     m = getattr(t, meth)
  21.     while meth not in t.__dict__:
  22.         t = t.__bases__[0]
  23.     vereq(m, t.__dict__[meth])
  24.     vereq(m(a), res)
  25.     bm = getattr(a, meth)
  26.     vereq(bm(), res)
  27.  
  28. def testbinop(a, b, res, expr="a+b", meth="__add__"):
  29.     if verbose: print "checking", expr
  30.     dict = {'a': a, 'b': b}
  31.  
  32.     # XXX Hack so this passes before 2.3 when -Qnew is specified.
  33.     if meth == "__div__" and 1/2 == 0.5:
  34.         meth = "__truediv__"
  35.  
  36.     vereq(eval(expr, dict), res)
  37.     t = type(a)
  38.     m = getattr(t, meth)
  39.     while meth not in t.__dict__:
  40.         t = t.__bases__[0]
  41.     vereq(m, t.__dict__[meth])
  42.     vereq(m(a, b), res)
  43.     bm = getattr(a, meth)
  44.     vereq(bm(b), res)
  45.  
  46. def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
  47.     if verbose: print "checking", expr
  48.     dict = {'a': a, 'b': b, 'c': c}
  49.     vereq(eval(expr, dict), res)
  50.     t = type(a)
  51.     m = getattr(t, meth)
  52.     while meth not in t.__dict__:
  53.         t = t.__bases__[0]
  54.     vereq(m, t.__dict__[meth])
  55.     vereq(m(a, b, c), res)
  56.     bm = getattr(a, meth)
  57.     vereq(bm(b, c), res)
  58.  
  59. def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
  60.     if verbose: print "checking", stmt
  61.     dict = {'a': deepcopy(a), 'b': b}
  62.     exec stmt in dict
  63.     vereq(dict['a'], res)
  64.     t = type(a)
  65.     m = getattr(t, meth)
  66.     while meth not in t.__dict__:
  67.         t = t.__bases__[0]
  68.     vereq(m, t.__dict__[meth])
  69.     dict['a'] = deepcopy(a)
  70.     m(dict['a'], b)
  71.     vereq(dict['a'], res)
  72.     dict['a'] = deepcopy(a)
  73.     bm = getattr(dict['a'], meth)
  74.     bm(b)
  75.     vereq(dict['a'], res)
  76.  
  77. def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
  78.     if verbose: print "checking", stmt
  79.     dict = {'a': deepcopy(a), 'b': b, 'c': c}
  80.     exec stmt in dict
  81.     vereq(dict['a'], res)
  82.     t = type(a)
  83.     m = getattr(t, meth)
  84.     while meth not in t.__dict__:
  85.         t = t.__bases__[0]
  86.     vereq(m, t.__dict__[meth])
  87.     dict['a'] = deepcopy(a)
  88.     m(dict['a'], b, c)
  89.     vereq(dict['a'], res)
  90.     dict['a'] = deepcopy(a)
  91.     bm = getattr(dict['a'], meth)
  92.     bm(b, c)
  93.     vereq(dict['a'], res)
  94.  
  95. def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
  96.     if verbose: print "checking", stmt
  97.     dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
  98.     exec stmt in dict
  99.     vereq(dict['a'], res)
  100.     t = type(a)
  101.     while meth not in t.__dict__:
  102.         t = t.__bases__[0]
  103.     m = getattr(t, meth)
  104.     vereq(m, t.__dict__[meth])
  105.     dict['a'] = deepcopy(a)
  106.     m(dict['a'], b, c, d)
  107.     vereq(dict['a'], res)
  108.     dict['a'] = deepcopy(a)
  109.     bm = getattr(dict['a'], meth)
  110.     bm(b, c, d)
  111.     vereq(dict['a'], res)
  112.  
  113. def class_docstrings():
  114.     class Classic:
  115.         "A classic docstring."
  116.     vereq(Classic.__doc__, "A classic docstring.")
  117.     vereq(Classic.__dict__['__doc__'], "A classic docstring.")
  118.  
  119.     class Classic2:
  120.         pass
  121.     verify(Classic2.__doc__ is None)
  122.  
  123.     class NewStatic(object):
  124.         "Another docstring."
  125.     vereq(NewStatic.__doc__, "Another docstring.")
  126.     vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
  127.  
  128.     class NewStatic2(object):
  129.         pass
  130.     verify(NewStatic2.__doc__ is None)
  131.  
  132.     class NewDynamic(object):
  133.         "Another docstring."
  134.     vereq(NewDynamic.__doc__, "Another docstring.")
  135.     vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
  136.  
  137.     class NewDynamic2(object):
  138.         pass
  139.     verify(NewDynamic2.__doc__ is None)
  140.  
  141. def lists():
  142.     if verbose: print "Testing list operations..."
  143.     testbinop([1], [2], [1,2], "a+b", "__add__")
  144.     testbinop([1,2,3], 2, 1, "b in a", "__contains__")
  145.     testbinop([1,2,3], 4, 0, "b in a", "__contains__")
  146.     testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
  147.     testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
  148.     testsetop([1], [2], [1,2], "a+=b", "__iadd__")
  149.     testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
  150.     testunop([1,2,3], 3, "len(a)", "__len__")
  151.     testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
  152.     testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
  153.     testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
  154.     testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
  155.  
  156. def dicts():
  157.     if verbose: print "Testing dict operations..."
  158.     testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
  159.     testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
  160.     testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
  161.     testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
  162.     d = {1:2,3:4}
  163.     l1 = []
  164.     for i in d.keys(): l1.append(i)
  165.     l = []
  166.     for i in iter(d): l.append(i)
  167.     vereq(l, l1)
  168.     l = []
  169.     for i in d.__iter__(): l.append(i)
  170.     vereq(l, l1)
  171.     l = []
  172.     for i in dict.__iter__(d): l.append(i)
  173.     vereq(l, l1)
  174.     d = {1:2, 3:4}
  175.     testunop(d, 2, "len(a)", "__len__")
  176.     vereq(eval(repr(d), {}), d)
  177.     vereq(eval(d.__repr__(), {}), d)
  178.     testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
  179.  
  180. def dict_constructor():
  181.     if verbose:
  182.         print "Testing dict constructor ..."
  183.     d = dict()
  184.     vereq(d, {})
  185.     d = dict({})
  186.     vereq(d, {})
  187.     d = dict(items={})
  188.     vereq(d, {})
  189.     d = dict({1: 2, 'a': 'b'})
  190.     vereq(d, {1: 2, 'a': 'b'})
  191.     vereq(d, dict(d.items()))
  192.     vereq(d, dict(items=d.iteritems()))
  193.     for badarg in 0, 0L, 0j, "0", [0], (0,):
  194.         try:
  195.             dict(badarg)
  196.         except TypeError:
  197.             pass
  198.         except ValueError:
  199.             if badarg == "0":
  200.                 # It's a sequence, and its elements are also sequences (gotta
  201.                 # love strings <wink>), but they aren't of length 2, so this
  202.                 # one seemed better as a ValueError than a TypeError.
  203.                 pass
  204.             else:
  205.                 raise TestFailed("no TypeError from dict(%r)" % badarg)
  206.         else:
  207.             raise TestFailed("no TypeError from dict(%r)" % badarg)
  208.     try:
  209.         dict(senseless={})
  210.     except TypeError:
  211.         pass
  212.     else:
  213.         raise TestFailed("no TypeError from dict(senseless={})")
  214.  
  215.     try:
  216.         dict({}, {})
  217.     except TypeError:
  218.         pass
  219.     else:
  220.         raise TestFailed("no TypeError from dict({}, {})")
  221.  
  222.     class Mapping:
  223.         # Lacks a .keys() method; will be added later.
  224.         dict = {1:2, 3:4, 'a':1j}
  225.  
  226.     try:
  227.         dict(Mapping())
  228.     except TypeError:
  229.         pass
  230.     else:
  231.         raise TestFailed("no TypeError from dict(incomplete mapping)")
  232.  
  233.     Mapping.keys = lambda self: self.dict.keys()
  234.     Mapping.__getitem__ = lambda self, i: self.dict[i]
  235.     d = dict(items=Mapping())
  236.     vereq(d, Mapping.dict)
  237.  
  238.     # Init from sequence of iterable objects, each producing a 2-sequence.
  239.     class AddressBookEntry:
  240.         def __init__(self, first, last):
  241.             self.first = first
  242.             self.last = last
  243.         def __iter__(self):
  244.             return iter([self.first, self.last])
  245.  
  246.     d = dict([AddressBookEntry('Tim', 'Warsaw'),
  247.               AddressBookEntry('Barry', 'Peters'),
  248.               AddressBookEntry('Tim', 'Peters'),
  249.               AddressBookEntry('Barry', 'Warsaw')])
  250.     vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
  251.  
  252.     d = dict(zip(range(4), range(1, 5)))
  253.     vereq(d, dict([(i, i+1) for i in range(4)]))
  254.  
  255.     # Bad sequence lengths.
  256.     for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
  257.         try:
  258.             dict(bad)
  259.         except ValueError:
  260.             pass
  261.         else:
  262.             raise TestFailed("no ValueError from dict(%r)" % bad)
  263.  
  264. def test_dir():
  265.     if verbose:
  266.         print "Testing dir() ..."
  267.     junk = 12
  268.     vereq(dir(), ['junk'])
  269.     del junk
  270.  
  271.     # Just make sure these don't blow up!
  272.     for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
  273.         dir(arg)
  274.  
  275.     # Try classic classes.
  276.     class C:
  277.         Cdata = 1
  278.         def Cmethod(self): pass
  279.  
  280.     cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
  281.     vereq(dir(C), cstuff)
  282.     verify('im_self' in dir(C.Cmethod))
  283.  
  284.     c = C()  # c.__doc__ is an odd thing to see here; ditto c.__module__.
  285.     vereq(dir(c), cstuff)
  286.  
  287.     c.cdata = 2
  288.     c.cmethod = lambda self: 0
  289.     vereq(dir(c), cstuff + ['cdata', 'cmethod'])
  290.     verify('im_self' in dir(c.Cmethod))
  291.  
  292.     class A(C):
  293.         Adata = 1
  294.         def Amethod(self): pass
  295.  
  296.     astuff = ['Adata', 'Amethod'] + cstuff
  297.     vereq(dir(A), astuff)
  298.     verify('im_self' in dir(A.Amethod))
  299.     a = A()
  300.     vereq(dir(a), astuff)
  301.     verify('im_self' in dir(a.Amethod))
  302.     a.adata = 42
  303.     a.amethod = lambda self: 3
  304.     vereq(dir(a), astuff + ['adata', 'amethod'])
  305.  
  306.     # The same, but with new-style classes.  Since these have object as a
  307.     # base class, a lot more gets sucked in.
  308.     def interesting(strings):
  309.         return [s for s in strings if not s.startswith('_')]
  310.  
  311.     class C(object):
  312.         Cdata = 1
  313.         def Cmethod(self): pass
  314.  
  315.     cstuff = ['Cdata', 'Cmethod']
  316.     vereq(interesting(dir(C)), cstuff)
  317.  
  318.     c = C()
  319.     vereq(interesting(dir(c)), cstuff)
  320.     verify('im_self' in dir(C.Cmethod))
  321.  
  322.     c.cdata = 2
  323.     c.cmethod = lambda self: 0
  324.     vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
  325.     verify('im_self' in dir(c.Cmethod))
  326.  
  327.     class A(C):
  328.         Adata = 1
  329.         def Amethod(self): pass
  330.  
  331.     astuff = ['Adata', 'Amethod'] + cstuff
  332.     vereq(interesting(dir(A)), astuff)
  333.     verify('im_self' in dir(A.Amethod))
  334.     a = A()
  335.     vereq(interesting(dir(a)), astuff)
  336.     a.adata = 42
  337.     a.amethod = lambda self: 3
  338.     vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
  339.     verify('im_self' in dir(a.Amethod))
  340.  
  341.     # Try a module subclass.
  342.     import sys
  343.     class M(type(sys)):
  344.         pass
  345.     minstance = M()
  346.     minstance.b = 2
  347.     minstance.a = 1
  348.     vereq(dir(minstance), ['a', 'b'])
  349.  
  350.     class M2(M):
  351.         def getdict(self):
  352.             return "Not a dict!"
  353.         __dict__ = property(getdict)
  354.  
  355.     m2instance = M2()
  356.     m2instance.b = 2
  357.     m2instance.a = 1
  358.     vereq(m2instance.__dict__, "Not a dict!")
  359.     try:
  360.         dir(m2instance)
  361.     except TypeError:
  362.         pass
  363.  
  364.     # Two essentially featureless objects, just inheriting stuff from
  365.     # object.
  366.     vereq(dir(None), dir(Ellipsis))
  367.  
  368.     # Nasty test case for proxied objects
  369.     class Wrapper(object):
  370.         def __init__(self, obj):
  371.             self.__obj = obj
  372.         def __repr__(self):
  373.             return "Wrapper(%s)" % repr(self.__obj)
  374.         def __getitem__(self, key):
  375.             return Wrapper(self.__obj[key])
  376.         def __len__(self):
  377.             return len(self.__obj)
  378.         def __getattr__(self, name):
  379.             return Wrapper(getattr(self.__obj, name))
  380.  
  381.     class C(object):
  382.         def __getclass(self):
  383.             return Wrapper(type(self))
  384.         __class__ = property(__getclass)
  385.  
  386.     dir(C()) # This used to segfault
  387.  
  388. binops = {
  389.     'add': '+',
  390.     'sub': '-',
  391.     'mul': '*',
  392.     'div': '/',
  393.     'mod': '%',
  394.     'divmod': 'divmod',
  395.     'pow': '**',
  396.     'lshift': '<<',
  397.     'rshift': '>>',
  398.     'and': '&',
  399.     'xor': '^',
  400.     'or': '|',
  401.     'cmp': 'cmp',
  402.     'lt': '<',
  403.     'le': '<=',
  404.     'eq': '==',
  405.     'ne': '!=',
  406.     'gt': '>',
  407.     'ge': '>=',
  408.     }
  409.  
  410. for name, expr in binops.items():
  411.     if expr.islower():
  412.         expr = expr + "(a, b)"
  413.     else:
  414.         expr = 'a %s b' % expr
  415.     binops[name] = expr
  416.  
  417. unops = {
  418.     'pos': '+',
  419.     'neg': '-',
  420.     'abs': 'abs',
  421.     'invert': '~',
  422.     'int': 'int',
  423.     'long': 'long',
  424.     'float': 'float',
  425.     'oct': 'oct',
  426.     'hex': 'hex',
  427.     }
  428.  
  429. for name, expr in unops.items():
  430.     if expr.islower():
  431.         expr = expr + "(a)"
  432.     else:
  433.         expr = '%s a' % expr
  434.     unops[name] = expr
  435.  
  436. def numops(a, b, skip=[]):
  437.     dict = {'a': a, 'b': b}
  438.     for name, expr in binops.items():
  439.         if name not in skip:
  440.             name = "__%s__" % name
  441.             if hasattr(a, name):
  442.                 res = eval(expr, dict)
  443.                 testbinop(a, b, res, expr, name)
  444.     for name, expr in unops.items():
  445.         if name not in skip:
  446.             name = "__%s__" % name
  447.             if hasattr(a, name):
  448.                 res = eval(expr, dict)
  449.                 testunop(a, res, expr, name)
  450.  
  451. def ints():
  452.     if verbose: print "Testing int operations..."
  453.     numops(100, 3)
  454.     # The following crashes in Python 2.2
  455.     vereq((1).__nonzero__(), 1)
  456.     vereq((0).__nonzero__(), 0)
  457.     # This returns 'NotImplemented' in Python 2.2
  458.     class C(int):
  459.         def __add__(self, other):
  460.             return NotImplemented
  461.     try:
  462.         C() + ""
  463.     except TypeError:
  464.         pass
  465.     else:
  466.         raise TestFailed, "NotImplemented should have caused TypeError"
  467.  
  468. def longs():
  469.     if verbose: print "Testing long operations..."
  470.     numops(100L, 3L)
  471.  
  472. def floats():
  473.     if verbose: print "Testing float operations..."
  474.     numops(100.0, 3.0)
  475.  
  476. def complexes():
  477.     if verbose: print "Testing complex operations..."
  478.     numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
  479.     class Number(complex):
  480.         __slots__ = ['prec']
  481.         def __new__(cls, *args, **kwds):
  482.             result = complex.__new__(cls, *args)
  483.             result.prec = kwds.get('prec', 12)
  484.             return result
  485.         def __repr__(self):
  486.             prec = self.prec
  487.             if self.imag == 0.0:
  488.                 return "%.*g" % (prec, self.real)
  489.             if self.real == 0.0:
  490.                 return "%.*gj" % (prec, self.imag)
  491.             return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
  492.         __str__ = __repr__
  493.  
  494.     a = Number(3.14, prec=6)
  495.     vereq(`a`, "3.14")
  496.     vereq(a.prec, 6)
  497.  
  498.     a = Number(a, prec=2)
  499.     vereq(`a`, "3.1")
  500.     vereq(a.prec, 2)
  501.  
  502.     a = Number(234.5)
  503.     vereq(`a`, "234.5")
  504.     vereq(a.prec, 12)
  505.  
  506. def spamlists():
  507.     if verbose: print "Testing spamlist operations..."
  508.     import copy, xxsubtype as spam
  509.     def spamlist(l, memo=None):
  510.         import xxsubtype as spam
  511.         return spam.spamlist(l)
  512.     # This is an ugly hack:
  513.     copy._deepcopy_dispatch[spam.spamlist] = spamlist
  514.  
  515.     testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
  516.     testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
  517.     testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
  518.     testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
  519.     testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
  520.                "a[b:c]", "__getslice__")
  521.     testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
  522.               "a+=b", "__iadd__")
  523.     testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
  524.     testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
  525.     testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
  526.     testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
  527.     testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
  528.     testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
  529.                spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
  530.     # Test subclassing
  531.     class C(spam.spamlist):
  532.         def foo(self): return 1
  533.     a = C()
  534.     vereq(a, [])
  535.     vereq(a.foo(), 1)
  536.     a.append(100)
  537.     vereq(a, [100])
  538.     vereq(a.getstate(), 0)
  539.     a.setstate(42)
  540.     vereq(a.getstate(), 42)
  541.  
  542. def spamdicts():
  543.     if verbose: print "Testing spamdict operations..."
  544.     import copy, xxsubtype as spam
  545.     def spamdict(d, memo=None):
  546.         import xxsubtype as spam
  547.         sd = spam.spamdict()
  548.         for k, v in d.items(): sd[k] = v
  549.         return sd
  550.     # This is an ugly hack:
  551.     copy._deepcopy_dispatch[spam.spamdict] = spamdict
  552.  
  553.     testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
  554.     testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
  555.     testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
  556.     testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
  557.     d = spamdict({1:2,3:4})
  558.     l1 = []
  559.     for i in d.keys(): l1.append(i)
  560.     l = []
  561.     for i in iter(d): l.append(i)
  562.     vereq(l, l1)
  563.     l = []
  564.     for i in d.__iter__(): l.append(i)
  565.     vereq(l, l1)
  566.     l = []
  567.     for i in type(spamdict({})).__iter__(d): l.append(i)
  568.     vereq(l, l1)
  569.     straightd = {1:2, 3:4}
  570.     spamd = spamdict(straightd)
  571.     testunop(spamd, 2, "len(a)", "__len__")
  572.     testunop(spamd, repr(straightd), "repr(a)", "__repr__")
  573.     testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
  574.                "a[b]=c", "__setitem__")
  575.     # Test subclassing
  576.     class C(spam.spamdict):
  577.         def foo(self): return 1
  578.     a = C()
  579.     vereq(a.items(), [])
  580.     vereq(a.foo(), 1)
  581.     a['foo'] = 'bar'
  582.     vereq(a.items(), [('foo', 'bar')])
  583.     vereq(a.getstate(), 0)
  584.     a.setstate(100)
  585.     vereq(a.getstate(), 100)
  586.  
  587. def pydicts():
  588.     if verbose: print "Testing Python subclass of dict..."
  589.     verify(issubclass(dict, dict))
  590.     verify(isinstance({}, dict))
  591.     d = dict()
  592.     vereq(d, {})
  593.     verify(d.__class__ is dict)
  594.     verify(isinstance(d, dict))
  595.     class C(dict):
  596.         state = -1
  597.         def __init__(self, *a, **kw):
  598.             if a:
  599.                 vereq(len(a), 1)
  600.                 self.state = a[0]
  601.             if kw:
  602.                 for k, v in kw.items(): self[v] = k
  603.         def __getitem__(self, key):
  604.             return self.get(key, 0)
  605.         def __setitem__(self, key, value):
  606.             verify(isinstance(key, type(0)))
  607.             dict.__setitem__(self, key, value)
  608.         def setstate(self, state):
  609.             self.state = state
  610.         def getstate(self):
  611.             return self.state
  612.     verify(issubclass(C, dict))
  613.     a1 = C(12)
  614.     vereq(a1.state, 12)
  615.     a2 = C(foo=1, bar=2)
  616.     vereq(a2[1] == 'foo' and a2[2], 'bar')
  617.     a = C()
  618.     vereq(a.state, -1)
  619.     vereq(a.getstate(), -1)
  620.     a.setstate(0)
  621.     vereq(a.state, 0)
  622.     vereq(a.getstate(), 0)
  623.     a.setstate(10)
  624.     vereq(a.state, 10)
  625.     vereq(a.getstate(), 10)
  626.     vereq(a[42], 0)
  627.     a[42] = 24
  628.     vereq(a[42], 24)
  629.     if verbose: print "pydict stress test ..."
  630.     N = 50
  631.     for i in range(N):
  632.         a[i] = C()
  633.         for j in range(N):
  634.             a[i][j] = i*j
  635.     for i in range(N):
  636.         for j in range(N):
  637.             vereq(a[i][j], i*j)
  638.  
  639. def pylists():
  640.     if verbose: print "Testing Python subclass of list..."
  641.     class C(list):
  642.         def __getitem__(self, i):
  643.             return list.__getitem__(self, i) + 100
  644.         def __getslice__(self, i, j):
  645.             return (i, j)
  646.     a = C()
  647.     a.extend([0,1,2])
  648.     vereq(a[0], 100)
  649.     vereq(a[1], 101)
  650.     vereq(a[2], 102)
  651.     vereq(a[100:200], (100,200))
  652.  
  653. def metaclass():
  654.     if verbose: print "Testing __metaclass__..."
  655.     class C:
  656.         __metaclass__ = type
  657.         def __init__(self):
  658.             self.__state = 0
  659.         def getstate(self):
  660.             return self.__state
  661.         def setstate(self, state):
  662.             self.__state = state
  663.     a = C()
  664.     vereq(a.getstate(), 0)
  665.     a.setstate(10)
  666.     vereq(a.getstate(), 10)
  667.     class D:
  668.         class __metaclass__(type):
  669.             def myself(cls): return cls
  670.     vereq(D.myself(), D)
  671.     d = D()
  672.     verify(d.__class__ is D)
  673.     class M1(type):
  674.         def __new__(cls, name, bases, dict):
  675.             dict['__spam__'] = 1
  676.             return type.__new__(cls, name, bases, dict)
  677.     class C:
  678.         __metaclass__ = M1
  679.     vereq(C.__spam__, 1)
  680.     c = C()
  681.     vereq(c.__spam__, 1)
  682.  
  683.     class _instance(object):
  684.         pass
  685.     class M2(object):
  686.         def __new__(cls, name, bases, dict):
  687.             self = object.__new__(cls)
  688.             self.name = name
  689.             self.bases = bases
  690.             self.dict = dict
  691.             return self
  692.         __new__ = staticmethod(__new__)
  693.         def __call__(self):
  694.             it = _instance()
  695.             # Early binding of methods
  696.             for key in self.dict:
  697.                 if key.startswith("__"):
  698.                     continue
  699.                 setattr(it, key, self.dict[key].__get__(it, self))
  700.             return it
  701.     class C:
  702.         __metaclass__ = M2
  703.         def spam(self):
  704.             return 42
  705.     vereq(C.name, 'C')
  706.     vereq(C.bases, ())
  707.     verify('spam' in C.dict)
  708.     c = C()
  709.     vereq(c.spam(), 42)
  710.  
  711.     # More metaclass examples
  712.  
  713.     class autosuper(type):
  714.         # Automatically add __super to the class
  715.         # This trick only works for dynamic classes
  716.         def __new__(metaclass, name, bases, dict):
  717.             cls = super(autosuper, metaclass).__new__(metaclass,
  718.                                                       name, bases, dict)
  719.             # Name mangling for __super removes leading underscores
  720.             while name[:1] == "_":
  721.                 name = name[1:]
  722.             if name:
  723.                 name = "_%s__super" % name
  724.             else:
  725.                 name = "__super"
  726.             setattr(cls, name, super(cls))
  727.             return cls
  728.     class A:
  729.         __metaclass__ = autosuper
  730.         def meth(self):
  731.             return "A"
  732.     class B(A):
  733.         def meth(self):
  734.             return "B" + self.__super.meth()
  735.     class C(A):
  736.         def meth(self):
  737.             return "C" + self.__super.meth()
  738.     class D(C, B):
  739.         def meth(self):
  740.             return "D" + self.__super.meth()
  741.     vereq(D().meth(), "DCBA")
  742.     class E(B, C):
  743.         def meth(self):
  744.             return "E" + self.__super.meth()
  745.     vereq(E().meth(), "EBCA")
  746.  
  747.     class autoproperty(type):
  748.         # Automatically create property attributes when methods
  749.         # named _get_x and/or _set_x are found
  750.         def __new__(metaclass, name, bases, dict):
  751.             hits = {}
  752.             for key, val in dict.iteritems():
  753.                 if key.startswith("_get_"):
  754.                     key = key[5:]
  755.                     get, set = hits.get(key, (None, None))
  756.                     get = val
  757.                     hits[key] = get, set
  758.                 elif key.startswith("_set_"):
  759.                     key = key[5:]
  760.                     get, set = hits.get(key, (None, None))
  761.                     set = val
  762.                     hits[key] = get, set
  763.             for key, (get, set) in hits.iteritems():
  764.                 dict[key] = property(get, set)
  765.             return super(autoproperty, metaclass).__new__(metaclass,
  766.                                                         name, bases, dict)
  767.     class A:
  768.         __metaclass__ = autoproperty
  769.         def _get_x(self):
  770.             return -self.__x
  771.         def _set_x(self, x):
  772.             self.__x = -x
  773.     a = A()
  774.     verify(not hasattr(a, "x"))
  775.     a.x = 12
  776.     vereq(a.x, 12)
  777.     vereq(a._A__x, -12)
  778.  
  779.     class multimetaclass(autoproperty, autosuper):
  780.         # Merge of multiple cooperating metaclasses
  781.         pass
  782.     class A:
  783.         __metaclass__ = multimetaclass
  784.         def _get_x(self):
  785.             return "A"
  786.     class B(A):
  787.         def _get_x(self):
  788.             return "B" + self.__super._get_x()
  789.     class C(A):
  790.         def _get_x(self):
  791.             return "C" + self.__super._get_x()
  792.     class D(C, B):
  793.         def _get_x(self):
  794.             return "D" + self.__super._get_x()
  795.     vereq(D().x, "DCBA")
  796.  
  797.     # Make sure type(x) doesn't call x.__class__.__init__
  798.     class T(type):
  799.         counter = 0
  800.         def __init__(self, *args):
  801.             T.counter += 1
  802.     class C:
  803.         __metaclass__ = T
  804.     vereq(T.counter, 1)
  805.     a = C()
  806.     vereq(type(a), C)
  807.     vereq(T.counter, 1)
  808.  
  809.     class C(object): pass
  810.     c = C()
  811.     try: c()
  812.     except TypeError: pass
  813.     else: raise TestError, "calling object w/o call method should raise TypeError"
  814.  
  815. def pymods():
  816.     if verbose: print "Testing Python subclass of module..."
  817.     log = []
  818.     import sys
  819.     MT = type(sys)
  820.     class MM(MT):
  821.         def __init__(self):
  822.             MT.__init__(self)
  823.         def __getattribute__(self, name):
  824.             log.append(("getattr", name))
  825.             return MT.__getattribute__(self, name)
  826.         def __setattr__(self, name, value):
  827.             log.append(("setattr", name, value))
  828.             MT.__setattr__(self, name, value)
  829.         def __delattr__(self, name):
  830.             log.append(("delattr", name))
  831.             MT.__delattr__(self, name)
  832.     a = MM()
  833.     a.foo = 12
  834.     x = a.foo
  835.     del a.foo
  836.     vereq(log, [("setattr", "foo", 12),
  837.                 ("getattr", "foo"),
  838.                 ("delattr", "foo")])
  839.  
  840. def multi():
  841.     if verbose: print "Testing multiple inheritance..."
  842.     class C(object):
  843.         def __init__(self):
  844.             self.__state = 0
  845.         def getstate(self):
  846.             return self.__state
  847.         def setstate(self, state):
  848.             self.__state = state
  849.     a = C()
  850.     vereq(a.getstate(), 0)
  851.     a.setstate(10)
  852.     vereq(a.getstate(), 10)
  853.     class D(dict, C):
  854.         def __init__(self):
  855.             type({}).__init__(self)
  856.             C.__init__(self)
  857.     d = D()
  858.     vereq(d.keys(), [])
  859.     d["hello"] = "world"
  860.     vereq(d.items(), [("hello", "world")])
  861.     vereq(d["hello"], "world")
  862.     vereq(d.getstate(), 0)
  863.     d.setstate(10)
  864.     vereq(d.getstate(), 10)
  865.     vereq(D.__mro__, (D, dict, C, object))
  866.  
  867.     # SF bug #442833
  868.     class Node(object):
  869.         def __int__(self):
  870.             return int(self.foo())
  871.         def foo(self):
  872.             return "23"
  873.     class Frag(Node, list):
  874.         def foo(self):
  875.             return "42"
  876.     vereq(Node().__int__(), 23)
  877.     vereq(int(Node()), 23)
  878.     vereq(Frag().__int__(), 42)
  879.     vereq(int(Frag()), 42)
  880.  
  881.     # MI mixing classic and new-style classes.
  882.  
  883.     class A:
  884.         x = 1
  885.  
  886.     class B(A):
  887.         pass
  888.  
  889.     class C(A):
  890.         x = 2
  891.  
  892.     class D(B, C):
  893.         pass
  894.     vereq(D.x, 1)
  895.  
  896.     # Classic MRO is preserved for a classic base class.
  897.     class E(D, object):
  898.         pass
  899.     vereq(E.__mro__, (E, D, B, A, C, object))
  900.     vereq(E.x, 1)
  901.  
  902.     # But with a mix of classic bases, their MROs are combined using
  903.     # new-style MRO.
  904.     class F(B, C, object):
  905.         pass
  906.     vereq(F.__mro__, (F, B, C, A, object))
  907.     vereq(F.x, 2)
  908.  
  909.     # Try something else.
  910.     class C:
  911.         def cmethod(self):
  912.             return "C a"
  913.         def all_method(self):
  914.             return "C b"
  915.  
  916.     class M1(C, object):
  917.         def m1method(self):
  918.             return "M1 a"
  919.         def all_method(self):
  920.             return "M1 b"
  921.  
  922.     vereq(M1.__mro__, (M1, C, object))
  923.     m = M1()
  924.     vereq(m.cmethod(), "C a")
  925.     vereq(m.m1method(), "M1 a")
  926.     vereq(m.all_method(), "M1 b")
  927.  
  928.     class D(C):
  929.         def dmethod(self):
  930.             return "D a"
  931.         def all_method(self):
  932.             return "D b"
  933.  
  934.     class M2(object, D):
  935.         def m2method(self):
  936.             return "M2 a"
  937.         def all_method(self):
  938.             return "M2 b"
  939.  
  940.     vereq(M2.__mro__, (M2, object, D, C))
  941.     m = M2()
  942.     vereq(m.cmethod(), "C a")
  943.     vereq(m.dmethod(), "D a")
  944.     vereq(m.m2method(), "M2 a")
  945.     vereq(m.all_method(), "M2 b")
  946.  
  947.     class M3(M1, object, M2):
  948.         def m3method(self):
  949.             return "M3 a"
  950.         def all_method(self):
  951.             return "M3 b"
  952.     # XXX Expected this (the commented-out result):
  953.     # vereq(M3.__mro__, (M3, M1, M2, object, D, C))
  954.     vereq(M3.__mro__, (M3, M1, M2, D, C, object))  # XXX ?
  955.     m = M3()
  956.     vereq(m.cmethod(), "C a")
  957.     vereq(m.dmethod(), "D a")
  958.     vereq(m.m1method(), "M1 a")
  959.     vereq(m.m2method(), "M2 a")
  960.     vereq(m.m3method(), "M3 a")
  961.     vereq(m.all_method(), "M3 b")
  962.  
  963.     class Classic:
  964.         pass
  965.     try:
  966.         class New(Classic):
  967.             __metaclass__ = type
  968.     except TypeError:
  969.         pass
  970.     else:
  971.         raise TestFailed, "new class with only classic bases - shouldn't be"
  972.  
  973. def diamond():
  974.     if verbose: print "Testing multiple inheritance special cases..."
  975.     class A(object):
  976.         def spam(self): return "A"
  977.     vereq(A().spam(), "A")
  978.     class B(A):
  979.         def boo(self): return "B"
  980.         def spam(self): return "B"
  981.     vereq(B().spam(), "B")
  982.     vereq(B().boo(), "B")
  983.     class C(A):
  984.         def boo(self): return "C"
  985.     vereq(C().spam(), "A")
  986.     vereq(C().boo(), "C")
  987.     class D(B, C): pass
  988.     vereq(D().spam(), "B")
  989.     vereq(D().boo(), "B")
  990.     vereq(D.__mro__, (D, B, C, A, object))
  991.     class E(C, B): pass
  992.     vereq(E().spam(), "B")
  993.     vereq(E().boo(), "C")
  994.     vereq(E.__mro__, (E, C, B, A, object))
  995.     class F(D, E): pass
  996.     vereq(F().spam(), "B")
  997.     vereq(F().boo(), "B")
  998.     vereq(F.__mro__, (F, D, E, B, C, A, object))
  999.     class G(E, D): pass
  1000.     vereq(G().spam(), "B")
  1001.     vereq(G().boo(), "C")
  1002.     vereq(G.__mro__, (G, E, D, C, B, A, object))
  1003.  
  1004. def objects():
  1005.     if verbose: print "Testing object class..."
  1006.     a = object()
  1007.     vereq(a.__class__, object)
  1008.     vereq(type(a), object)
  1009.     b = object()
  1010.     verify(a is not b)
  1011.     verify(not hasattr(a, "foo"))
  1012.     try:
  1013.         a.foo = 12
  1014.     except (AttributeError, TypeError):
  1015.         pass
  1016.     else:
  1017.         verify(0, "object() should not allow setting a foo attribute")
  1018.     verify(not hasattr(object(), "__dict__"))
  1019.  
  1020.     class Cdict(object):
  1021.         pass
  1022.     x = Cdict()
  1023.     vereq(x.__dict__, {})
  1024.     x.foo = 1
  1025.     vereq(x.foo, 1)
  1026.     vereq(x.__dict__, {'foo': 1})
  1027.  
  1028. def slots():
  1029.     if verbose: print "Testing __slots__..."
  1030.     class C0(object):
  1031.         __slots__ = []
  1032.     x = C0()
  1033.     verify(not hasattr(x, "__dict__"))
  1034.     verify(not hasattr(x, "foo"))
  1035.  
  1036.     class C1(object):
  1037.         __slots__ = ['a']
  1038.     x = C1()
  1039.     verify(not hasattr(x, "__dict__"))
  1040.     verify(not hasattr(x, "a"))
  1041.     x.a = 1
  1042.     vereq(x.a, 1)
  1043.     x.a = None
  1044.     veris(x.a, None)
  1045.     del x.a
  1046.     verify(not hasattr(x, "a"))
  1047.  
  1048.     class C3(object):
  1049.         __slots__ = ['a', 'b', 'c']
  1050.     x = C3()
  1051.     verify(not hasattr(x, "__dict__"))
  1052.     verify(not hasattr(x, 'a'))
  1053.     verify(not hasattr(x, 'b'))
  1054.     verify(not hasattr(x, 'c'))
  1055.     x.a = 1
  1056.     x.b = 2
  1057.     x.c = 3
  1058.     vereq(x.a, 1)
  1059.     vereq(x.b, 2)
  1060.     vereq(x.c, 3)
  1061.  
  1062.     # Test leaks
  1063.     class Counted(object):
  1064.         counter = 0    # counts the number of instances alive
  1065.         def __init__(self):
  1066.             Counted.counter += 1
  1067.         def __del__(self):
  1068.             Counted.counter -= 1
  1069.     class C(object):
  1070.         __slots__ = ['a', 'b', 'c']
  1071.     x = C()
  1072.     x.a = Counted()
  1073.     x.b = Counted()
  1074.     x.c = Counted()
  1075.     vereq(Counted.counter, 3)
  1076.     del x
  1077.     vereq(Counted.counter, 0)
  1078.     class D(C):
  1079.         pass
  1080.     x = D()
  1081.     x.a = Counted()
  1082.     x.z = Counted()
  1083.     vereq(Counted.counter, 2)
  1084.     del x
  1085.     vereq(Counted.counter, 0)
  1086.     class E(D):
  1087.         __slots__ = ['e']
  1088.     x = E()
  1089.     x.a = Counted()
  1090.     x.z = Counted()
  1091.     x.e = Counted()
  1092.     vereq(Counted.counter, 3)
  1093.     del x
  1094.     vereq(Counted.counter, 0)
  1095.  
  1096.     # Test cyclical leaks [SF bug 519621]
  1097.     class F(object):
  1098.         __slots__ = ['a', 'b']
  1099.     log = []
  1100.     s = F()
  1101.     s.a = [Counted(), s]
  1102.     vereq(Counted.counter, 1)
  1103.     s = None
  1104.     import gc
  1105.     gc.collect()
  1106.     vereq(Counted.counter, 0)
  1107.  
  1108.     # Test lookup leaks [SF bug 572567]
  1109.     import sys,gc
  1110.     class G(object):
  1111.         def __cmp__(self, other):
  1112.             return 0
  1113.     g = G()
  1114.     orig_objects = len(gc.get_objects())
  1115.     for i in xrange(10):
  1116.         g==g
  1117.     new_objects = len(gc.get_objects())
  1118.     vereq(orig_objects, new_objects)
  1119.  
  1120. def dynamics():
  1121.     if verbose: print "Testing class attribute propagation..."
  1122.     class D(object):
  1123.         pass
  1124.     class E(D):
  1125.         pass
  1126.     class F(D):
  1127.         pass
  1128.     D.foo = 1
  1129.     vereq(D.foo, 1)
  1130.     # Test that dynamic attributes are inherited
  1131.     vereq(E.foo, 1)
  1132.     vereq(F.foo, 1)
  1133.     # Test dynamic instances
  1134.     class C(object):
  1135.         pass
  1136.     a = C()
  1137.     verify(not hasattr(a, "foobar"))
  1138.     C.foobar = 2
  1139.     vereq(a.foobar, 2)
  1140.     C.method = lambda self: 42
  1141.     vereq(a.method(), 42)
  1142.     C.__repr__ = lambda self: "C()"
  1143.     vereq(repr(a), "C()")
  1144.     C.__int__ = lambda self: 100
  1145.     vereq(int(a), 100)
  1146.     vereq(a.foobar, 2)
  1147.     verify(not hasattr(a, "spam"))
  1148.     def mygetattr(self, name):
  1149.         if name == "spam":
  1150.             return "spam"
  1151.         raise AttributeError
  1152.     C.__getattr__ = mygetattr
  1153.     vereq(a.spam, "spam")
  1154.     a.new = 12
  1155.     vereq(a.new, 12)
  1156.     def mysetattr(self, name, value):
  1157.         if name == "spam":
  1158.             raise AttributeError
  1159.         return object.__setattr__(self, name, value)
  1160.     C.__setattr__ = mysetattr
  1161.     try:
  1162.         a.spam = "not spam"
  1163.     except AttributeError:
  1164.         pass
  1165.     else:
  1166.         verify(0, "expected AttributeError")
  1167.     vereq(a.spam, "spam")
  1168.     class D(C):
  1169.         pass
  1170.     d = D()
  1171.     d.foo = 1
  1172.     vereq(d.foo, 1)
  1173.  
  1174.     # Test handling of int*seq and seq*int
  1175.     class I(int):
  1176.         pass
  1177.     vereq("a"*I(2), "aa")
  1178.     vereq(I(2)*"a", "aa")
  1179.     vereq(2*I(3), 6)
  1180.     vereq(I(3)*2, 6)
  1181.     vereq(I(3)*I(2), 6)
  1182.  
  1183.     # Test handling of long*seq and seq*long
  1184.     class L(long):
  1185.         pass
  1186.     vereq("a"*L(2L), "aa")
  1187.     vereq(L(2L)*"a", "aa")
  1188.     vereq(2*L(3), 6)
  1189.     vereq(L(3)*2, 6)
  1190.     vereq(L(3)*L(2), 6)
  1191.  
  1192.     # Test comparison of classes with dynamic metaclasses
  1193.     class dynamicmetaclass(type):
  1194.         pass
  1195.     class someclass:
  1196.         __metaclass__ = dynamicmetaclass
  1197.     verify(someclass != object)
  1198.  
  1199. def errors():
  1200.     if verbose: print "Testing errors..."
  1201.  
  1202.     try:
  1203.         class C(list, dict):
  1204.             pass
  1205.     except TypeError:
  1206.         pass
  1207.     else:
  1208.         verify(0, "inheritance from both list and dict should be illegal")
  1209.  
  1210.     try:
  1211.         class C(object, None):
  1212.             pass
  1213.     except TypeError:
  1214.         pass
  1215.     else:
  1216.         verify(0, "inheritance from non-type should be illegal")
  1217.     class Classic:
  1218.         pass
  1219.  
  1220.     try:
  1221.         class C(type(len)):
  1222.             pass
  1223.     except TypeError:
  1224.         pass
  1225.     else:
  1226.         verify(0, "inheritance from CFunction should be illegal")
  1227.  
  1228.     try:
  1229.         class C(object):
  1230.             __slots__ = 1
  1231.     except TypeError:
  1232.         pass
  1233.     else:
  1234.         verify(0, "__slots__ = 1 should be illegal")
  1235.  
  1236.     try:
  1237.         class C(object):
  1238.             __slots__ = [1]
  1239.     except TypeError:
  1240.         pass
  1241.     else:
  1242.         verify(0, "__slots__ = [1] should be illegal")
  1243.  
  1244. def classmethods():
  1245.     if verbose: print "Testing class methods..."
  1246.     class C(object):
  1247.         def foo(*a): return a
  1248.         goo = classmethod(foo)
  1249.     c = C()
  1250.     vereq(C.goo(1), (C, 1))
  1251.     vereq(c.goo(1), (C, 1))
  1252.     vereq(c.foo(1), (c, 1))
  1253.     class D(C):
  1254.         pass
  1255.     d = D()
  1256.     vereq(D.goo(1), (D, 1))
  1257.     vereq(d.goo(1), (D, 1))
  1258.     vereq(d.foo(1), (d, 1))
  1259.     vereq(D.foo(d, 1), (d, 1))
  1260.     # Test for a specific crash (SF bug 528132)
  1261.     def f(cls, arg): return (cls, arg)
  1262.     ff = classmethod(f)
  1263.     vereq(ff.__get__(0, int)(42), (int, 42))
  1264.     vereq(ff.__get__(0)(42), (int, 42))
  1265.  
  1266.     # Test super() with classmethods (SF bug 535444)
  1267.     veris(C.goo.im_self, C)
  1268.     veris(D.goo.im_self, D)
  1269.     veris(super(D,D).goo.im_self, D)
  1270.     veris(super(D,d).goo.im_self, D)
  1271.     vereq(super(D,D).goo(), (D,))
  1272.     vereq(super(D,d).goo(), (D,))
  1273.  
  1274. def staticmethods():
  1275.     if verbose: print "Testing static methods..."
  1276.     class C(object):
  1277.         def foo(*a): return a
  1278.         goo = staticmethod(foo)
  1279.     c = C()
  1280.     vereq(C.goo(1), (1,))
  1281.     vereq(c.goo(1), (1,))
  1282.     vereq(c.foo(1), (c, 1,))
  1283.     class D(C):
  1284.         pass
  1285.     d = D()
  1286.     vereq(D.goo(1), (1,))
  1287.     vereq(d.goo(1), (1,))
  1288.     vereq(d.foo(1), (d, 1))
  1289.     vereq(D.foo(d, 1), (d, 1))
  1290.  
  1291. def classic():
  1292.     if verbose: print "Testing classic classes..."
  1293.     class C:
  1294.         def foo(*a): return a
  1295.         goo = classmethod(foo)
  1296.     c = C()
  1297.     vereq(C.goo(1), (C, 1))
  1298.     vereq(c.goo(1), (C, 1))
  1299.     vereq(c.foo(1), (c, 1))
  1300.     class D(C):
  1301.         pass
  1302.     d = D()
  1303.     vereq(D.goo(1), (D, 1))
  1304.     vereq(d.goo(1), (D, 1))
  1305.     vereq(d.foo(1), (d, 1))
  1306.     vereq(D.foo(d, 1), (d, 1))
  1307.     class E: # *not* subclassing from C
  1308.         foo = C.foo
  1309.     vereq(E().foo, C.foo) # i.e., unbound
  1310.     verify(repr(C.foo.__get__(C())).startswith("<bound method "))
  1311.  
  1312. def compattr():
  1313.     if verbose: print "Testing computed attributes..."
  1314.     class C(object):
  1315.         class computed_attribute(object):
  1316.             def __init__(self, get, set=None, delete=None):
  1317.                 self.__get = get
  1318.                 self.__set = set
  1319.                 self.__delete = delete
  1320.             def __get__(self, obj, type=None):
  1321.                 return self.__get(obj)
  1322.             def __set__(self, obj, value):
  1323.                 return self.__set(obj, value)
  1324.             def __delete__(self, obj):
  1325.                 return self.__delete(obj)
  1326.         def __init__(self):
  1327.             self.__x = 0
  1328.         def __get_x(self):
  1329.             x = self.__x
  1330.             self.__x = x+1
  1331.             return x
  1332.         def __set_x(self, x):
  1333.             self.__x = x
  1334.         def __delete_x(self):
  1335.             del self.__x
  1336.         x = computed_attribute(__get_x, __set_x, __delete_x)
  1337.     a = C()
  1338.     vereq(a.x, 0)
  1339.     vereq(a.x, 1)
  1340.     a.x = 10
  1341.     vereq(a.x, 10)
  1342.     vereq(a.x, 11)
  1343.     del a.x
  1344.     vereq(hasattr(a, 'x'), 0)
  1345.  
  1346. def newslot():
  1347.     if verbose: print "Testing __new__ slot override..."
  1348.     class C(list):
  1349.         def __new__(cls):
  1350.             self = list.__new__(cls)
  1351.             self.foo = 1
  1352.             return self
  1353.         def __init__(self):
  1354.             self.foo = self.foo + 2
  1355.     a = C()
  1356.     vereq(a.foo, 3)
  1357.     verify(a.__class__ is C)
  1358.     class D(C):
  1359.         pass
  1360.     b = D()
  1361.     vereq(b.foo, 3)
  1362.     verify(b.__class__ is D)
  1363.  
  1364. def altmro():
  1365.     if verbose: print "Testing mro() and overriding it..."
  1366.     class A(object):
  1367.         def f(self): return "A"
  1368.     class B(A):
  1369.         pass
  1370.     class C(A):
  1371.         def f(self): return "C"
  1372.     class D(B, C):
  1373.         pass
  1374.     vereq(D.mro(), [D, B, C, A, object])
  1375.     vereq(D.__mro__, (D, B, C, A, object))
  1376.     vereq(D().f(), "C")
  1377.     class PerverseMetaType(type):
  1378.         def mro(cls):
  1379.             L = type.mro(cls)
  1380.             L.reverse()
  1381.             return L
  1382.     class X(A,B,C,D):
  1383.         __metaclass__ = PerverseMetaType
  1384.     vereq(X.__mro__, (object, A, C, B, D, X))
  1385.     vereq(X().f(), "A")
  1386.  
  1387. def overloading():
  1388.     if verbose: print "Testing operator overloading..."
  1389.  
  1390.     class B(object):
  1391.         "Intermediate class because object doesn't have a __setattr__"
  1392.  
  1393.     class C(B):
  1394.  
  1395.         def __getattr__(self, name):
  1396.             if name == "foo":
  1397.                 return ("getattr", name)
  1398.             else:
  1399.                 raise AttributeError
  1400.         def __setattr__(self, name, value):
  1401.             if name == "foo":
  1402.                 self.setattr = (name, value)
  1403.             else:
  1404.                 return B.__setattr__(self, name, value)
  1405.         def __delattr__(self, name):
  1406.             if name == "foo":
  1407.                 self.delattr = name
  1408.             else:
  1409.                 return B.__delattr__(self, name)
  1410.  
  1411.         def __getitem__(self, key):
  1412.             return ("getitem", key)
  1413.         def __setitem__(self, key, value):
  1414.             self.setitem = (key, value)
  1415.         def __delitem__(self, key):
  1416.             self.delitem = key
  1417.  
  1418.         def __getslice__(self, i, j):
  1419.             return ("getslice", i, j)
  1420.         def __setslice__(self, i, j, value):
  1421.             self.setslice = (i, j, value)
  1422.         def __delslice__(self, i, j):
  1423.             self.delslice = (i, j)
  1424.  
  1425.     a = C()
  1426.     vereq(a.foo, ("getattr", "foo"))
  1427.     a.foo = 12
  1428.     vereq(a.setattr, ("foo", 12))
  1429.     del a.foo
  1430.     vereq(a.delattr, "foo")
  1431.  
  1432.     vereq(a[12], ("getitem", 12))
  1433.     a[12] = 21
  1434.     vereq(a.setitem, (12, 21))
  1435.     del a[12]
  1436.     vereq(a.delitem, 12)
  1437.  
  1438.     vereq(a[0:10], ("getslice", 0, 10))
  1439.     a[0:10] = "foo"
  1440.     vereq(a.setslice, (0, 10, "foo"))
  1441.     del a[0:10]
  1442.     vereq(a.delslice, (0, 10))
  1443.  
  1444. def methods():
  1445.     if verbose: print "Testing methods..."
  1446.     class C(object):
  1447.         def __init__(self, x):
  1448.             self.x = x
  1449.         def foo(self):
  1450.             return self.x
  1451.     c1 = C(1)
  1452.     vereq(c1.foo(), 1)
  1453.     class D(C):
  1454.         boo = C.foo
  1455.         goo = c1.foo
  1456.     d2 = D(2)
  1457.     vereq(d2.foo(), 2)
  1458.     vereq(d2.boo(), 2)
  1459.     vereq(d2.goo(), 1)
  1460.     class E(object):
  1461.         foo = C.foo
  1462.     vereq(E().foo, C.foo) # i.e., unbound
  1463.     verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
  1464.  
  1465. def specials():
  1466.     # Test operators like __hash__ for which a built-in default exists
  1467.     if verbose: print "Testing special operators..."
  1468.     # Test the default behavior for static classes
  1469.     class C(object):
  1470.         def __getitem__(self, i):
  1471.             if 0 <= i < 10: return i
  1472.             raise IndexError
  1473.     c1 = C()
  1474.     c2 = C()
  1475.     verify(not not c1)
  1476.     vereq(hash(c1), id(c1))
  1477.     vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
  1478.     vereq(c1, c1)
  1479.     verify(c1 != c2)
  1480.     verify(not c1 != c1)
  1481.     verify(not c1 == c2)
  1482.     # Note that the module name appears in str/repr, and that varies
  1483.     # depending on whether this test is run standalone or from a framework.
  1484.     verify(str(c1).find('C object at ') >= 0)
  1485.     vereq(str(c1), repr(c1))
  1486.     verify(-1 not in c1)
  1487.     for i in range(10):
  1488.         verify(i in c1)
  1489.     verify(10 not in c1)
  1490.     # Test the default behavior for dynamic classes
  1491.     class D(object):
  1492.         def __getitem__(self, i):
  1493.             if 0 <= i < 10: return i
  1494.             raise IndexError
  1495.     d1 = D()
  1496.     d2 = D()
  1497.     verify(not not d1)
  1498.     vereq(hash(d1), id(d1))
  1499.     vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
  1500.     vereq(d1, d1)
  1501.     verify(d1 != d2)
  1502.     verify(not d1 != d1)
  1503.     verify(not d1 == d2)
  1504.     # Note that the module name appears in str/repr, and that varies
  1505.     # depending on whether this test is run standalone or from a framework.
  1506.     verify(str(d1).find('D object at ') >= 0)
  1507.     vereq(str(d1), repr(d1))
  1508.     verify(-1 not in d1)
  1509.     for i in range(10):
  1510.         verify(i in d1)
  1511.     verify(10 not in d1)
  1512.     # Test overridden behavior for static classes
  1513.     class Proxy(object):
  1514.         def __init__(self, x):
  1515.             self.x = x
  1516.         def __nonzero__(self):
  1517.             return not not self.x
  1518.         def __hash__(self):
  1519.             return hash(self.x)
  1520.         def __eq__(self, other):
  1521.             return self.x == other
  1522.         def __ne__(self, other):
  1523.             return self.x != other
  1524.         def __cmp__(self, other):
  1525.             return cmp(self.x, other.x)
  1526.         def __str__(self):
  1527.             return "Proxy:%s" % self.x
  1528.         def __repr__(self):
  1529.             return "Proxy(%r)" % self.x
  1530.         def __contains__(self, value):
  1531.             return value in self.x
  1532.     p0 = Proxy(0)
  1533.     p1 = Proxy(1)
  1534.     p_1 = Proxy(-1)
  1535.     verify(not p0)
  1536.     verify(not not p1)
  1537.     vereq(hash(p0), hash(0))
  1538.     vereq(p0, p0)
  1539.     verify(p0 != p1)
  1540.     verify(not p0 != p0)
  1541.     vereq(not p0, p1)
  1542.     vereq(cmp(p0, p1), -1)
  1543.     vereq(cmp(p0, p0), 0)
  1544.     vereq(cmp(p0, p_1), 1)
  1545.     vereq(str(p0), "Proxy:0")
  1546.     vereq(repr(p0), "Proxy(0)")
  1547.     p10 = Proxy(range(10))
  1548.     verify(-1 not in p10)
  1549.     for i in range(10):
  1550.         verify(i in p10)
  1551.     verify(10 not in p10)
  1552.     # Test overridden behavior for dynamic classes
  1553.     class DProxy(object):
  1554.         def __init__(self, x):
  1555.             self.x = x
  1556.         def __nonzero__(self):
  1557.             return not not self.x
  1558.         def __hash__(self):
  1559.             return hash(self.x)
  1560.         def __eq__(self, other):
  1561.             return self.x == other
  1562.         def __ne__(self, other):
  1563.             return self.x != other
  1564.         def __cmp__(self, other):
  1565.             return cmp(self.x, other.x)
  1566.         def __str__(self):
  1567.             return "DProxy:%s" % self.x
  1568.         def __repr__(self):
  1569.             return "DProxy(%r)" % self.x
  1570.         def __contains__(self, value):
  1571.             return value in self.x
  1572.     p0 = DProxy(0)
  1573.     p1 = DProxy(1)
  1574.     p_1 = DProxy(-1)
  1575.     verify(not p0)
  1576.     verify(not not p1)
  1577.     vereq(hash(p0), hash(0))
  1578.     vereq(p0, p0)
  1579.     verify(p0 != p1)
  1580.     verify(not p0 != p0)
  1581.     vereq(not p0, p1)
  1582.     vereq(cmp(p0, p1), -1)
  1583.     vereq(cmp(p0, p0), 0)
  1584.     vereq(cmp(p0, p_1), 1)
  1585.     vereq(str(p0), "DProxy:0")
  1586.     vereq(repr(p0), "DProxy(0)")
  1587.     p10 = DProxy(range(10))
  1588.     verify(-1 not in p10)
  1589.     for i in range(10):
  1590.         verify(i in p10)
  1591.     verify(10 not in p10)
  1592.     # Safety test for __cmp__
  1593.     def unsafecmp(a, b):
  1594.         try:
  1595.             a.__class__.__cmp__(a, b)
  1596.         except TypeError:
  1597.             pass
  1598.         else:
  1599.             raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
  1600.                 a.__class__, a, b)
  1601.     unsafecmp(u"123", "123")
  1602.     unsafecmp("123", u"123")
  1603.     unsafecmp(1, 1.0)
  1604.     unsafecmp(1.0, 1)
  1605.     unsafecmp(1, 1L)
  1606.     unsafecmp(1L, 1)
  1607.  
  1608. def weakrefs():
  1609.     if verbose: print "Testing weak references..."
  1610.     import weakref
  1611.     class C(object):
  1612.         pass
  1613.     c = C()
  1614.     r = weakref.ref(c)
  1615.     verify(r() is c)
  1616.     del c
  1617.     verify(r() is None)
  1618.     del r
  1619.     class NoWeak(object):
  1620.         __slots__ = ['foo']
  1621.     no = NoWeak()
  1622.     try:
  1623.         weakref.ref(no)
  1624.     except TypeError, msg:
  1625.         verify(str(msg).find("weak reference") >= 0)
  1626.     else:
  1627.         verify(0, "weakref.ref(no) should be illegal")
  1628.     class Weak(object):
  1629.         __slots__ = ['foo', '__weakref__']
  1630.     yes = Weak()
  1631.     r = weakref.ref(yes)
  1632.     verify(r() is yes)
  1633.     del yes
  1634.     verify(r() is None)
  1635.     del r
  1636.  
  1637. def properties():
  1638.     if verbose: print "Testing property..."
  1639.     class C(object):
  1640.         def getx(self):
  1641.             return self.__x
  1642.         def setx(self, value):
  1643.             self.__x = value
  1644.         def delx(self):
  1645.             del self.__x
  1646.         x = property(getx, setx, delx, doc="I'm the x property.")
  1647.     a = C()
  1648.     verify(not hasattr(a, "x"))
  1649.     a.x = 42
  1650.     vereq(a._C__x, 42)
  1651.     vereq(a.x, 42)
  1652.     del a.x
  1653.     verify(not hasattr(a, "x"))
  1654.     verify(not hasattr(a, "_C__x"))
  1655.     C.x.__set__(a, 100)
  1656.     vereq(C.x.__get__(a), 100)
  1657.     C.x.__delete__(a)
  1658.     verify(not hasattr(a, "x"))
  1659.  
  1660.     raw = C.__dict__['x']
  1661.     verify(isinstance(raw, property))
  1662.  
  1663.     attrs = dir(raw)
  1664.     verify("__doc__" in attrs)
  1665.     verify("fget" in attrs)
  1666.     verify("fset" in attrs)
  1667.     verify("fdel" in attrs)
  1668.  
  1669.     vereq(raw.__doc__, "I'm the x property.")
  1670.     verify(raw.fget is C.__dict__['getx'])
  1671.     verify(raw.fset is C.__dict__['setx'])
  1672.     verify(raw.fdel is C.__dict__['delx'])
  1673.  
  1674.     for attr in "__doc__", "fget", "fset", "fdel":
  1675.         try:
  1676.             setattr(raw, attr, 42)
  1677.         except TypeError, msg:
  1678.             if str(msg).find('readonly') < 0:
  1679.                 raise TestFailed("when setting readonly attr %r on a "
  1680.                                  "property, got unexpected TypeError "
  1681.                                  "msg %r" % (attr, str(msg)))
  1682.         else:
  1683.             raise TestFailed("expected TypeError from trying to set "
  1684.                              "readonly %r attr on a property" % attr)
  1685.  
  1686. def supers():
  1687.     if verbose: print "Testing super..."
  1688.  
  1689.     class A(object):
  1690.         def meth(self, a):
  1691.             return "A(%r)" % a
  1692.  
  1693.     vereq(A().meth(1), "A(1)")
  1694.  
  1695.     class B(A):
  1696.         def __init__(self):
  1697.             self.__super = super(B, self)
  1698.         def meth(self, a):
  1699.             return "B(%r)" % a + self.__super.meth(a)
  1700.  
  1701.     vereq(B().meth(2), "B(2)A(2)")
  1702.  
  1703.     class C(A):
  1704.         def meth(self, a):
  1705.             return "C(%r)" % a + self.__super.meth(a)
  1706.     C._C__super = super(C)
  1707.  
  1708.     vereq(C().meth(3), "C(3)A(3)")
  1709.  
  1710.     class D(C, B):
  1711.         def meth(self, a):
  1712.             return "D(%r)" % a + super(D, self).meth(a)
  1713.  
  1714.     vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
  1715.  
  1716.     # Test for subclassing super
  1717.  
  1718.     class mysuper(super):
  1719.         def __init__(self, *args):
  1720.             return super(mysuper, self).__init__(*args)
  1721.  
  1722.     class E(D):
  1723.         def meth(self, a):
  1724.             return "E(%r)" % a + mysuper(E, self).meth(a)
  1725.  
  1726.     vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
  1727.  
  1728.     class F(E):
  1729.         def meth(self, a):
  1730.             s = self.__super
  1731.             return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
  1732.     F._F__super = mysuper(F)
  1733.  
  1734.     vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
  1735.  
  1736.     # Make sure certain errors are raised
  1737.  
  1738.     try:
  1739.         super(D, 42)
  1740.     except TypeError:
  1741.         pass
  1742.     else:
  1743.         raise TestFailed, "shouldn't allow super(D, 42)"
  1744.  
  1745.     try:
  1746.         super(D, C())
  1747.     except TypeError:
  1748.         pass
  1749.     else:
  1750.         raise TestFailed, "shouldn't allow super(D, C())"
  1751.  
  1752.     try:
  1753.         super(D).__get__(12)
  1754.     except TypeError:
  1755.         pass
  1756.     else:
  1757.         raise TestFailed, "shouldn't allow super(D).__get__(12)"
  1758.  
  1759.     try:
  1760.         super(D).__get__(C())
  1761.     except TypeError:
  1762.         pass
  1763.     else:
  1764.         raise TestFailed, "shouldn't allow super(D).__get__(C())"
  1765.  
  1766. def inherits():
  1767.     if verbose: print "Testing inheritance from basic types..."
  1768.  
  1769.     class hexint(int):
  1770.         def __repr__(self):
  1771.             return hex(self)
  1772.         def __add__(self, other):
  1773.             return hexint(int.__add__(self, other))
  1774.         # (Note that overriding __radd__ doesn't work,
  1775.         # because the int type gets first dibs.)
  1776.     vereq(repr(hexint(7) + 9), "0x10")
  1777.     vereq(repr(hexint(1000) + 7), "0x3ef")
  1778.     a = hexint(12345)
  1779.     vereq(a, 12345)
  1780.     vereq(int(a), 12345)
  1781.     verify(int(a).__class__ is int)
  1782.     vereq(hash(a), hash(12345))
  1783.     verify((+a).__class__ is int)
  1784.     verify((a >> 0).__class__ is int)
  1785.     verify((a << 0).__class__ is int)
  1786.     verify((hexint(0) << 12).__class__ is int)
  1787.     verify((hexint(0) >> 12).__class__ is int)
  1788.  
  1789.     class octlong(long):
  1790.         __slots__ = []
  1791.         def __str__(self):
  1792.             s = oct(self)
  1793.             if s[-1] == 'L':
  1794.                 s = s[:-1]
  1795.             return s
  1796.         def __add__(self, other):
  1797.             return self.__class__(super(octlong, self).__add__(other))
  1798.         __radd__ = __add__
  1799.     vereq(str(octlong(3) + 5), "010")
  1800.     # (Note that overriding __radd__ here only seems to work
  1801.     # because the example uses a short int left argument.)
  1802.     vereq(str(5 + octlong(3000)), "05675")
  1803.     a = octlong(12345)
  1804.     vereq(a, 12345L)
  1805.     vereq(long(a), 12345L)
  1806.     vereq(hash(a), hash(12345L))
  1807.     verify(long(a).__class__ is long)
  1808.     verify((+a).__class__ is long)
  1809.     verify((-a).__class__ is long)
  1810.     verify((-octlong(0)).__class__ is long)
  1811.     verify((a >> 0).__class__ is long)
  1812.     verify((a << 0).__class__ is long)
  1813.     verify((a - 0).__class__ is long)
  1814.     verify((a * 1).__class__ is long)
  1815.     verify((a ** 1).__class__ is long)
  1816.     verify((a // 1).__class__ is long)
  1817.     verify((1 * a).__class__ is long)
  1818.     verify((a | 0).__class__ is long)
  1819.     verify((a ^ 0).__class__ is long)
  1820.     verify((a & -1L).__class__ is long)
  1821.     verify((octlong(0) << 12).__class__ is long)
  1822.     verify((octlong(0) >> 12).__class__ is long)
  1823.     verify(abs(octlong(0)).__class__ is long)
  1824.  
  1825.     # Because octlong overrides __add__, we can't check the absence of +0
  1826.     # optimizations using octlong.
  1827.     class longclone(long):
  1828.         pass
  1829.     a = longclone(1)
  1830.     verify((a + 0).__class__ is long)
  1831.     verify((0 + a).__class__ is long)
  1832.  
  1833.     # Check that negative clones don't segfault
  1834.     a = longclone(-1)
  1835.     vereq(a.__dict__, {})
  1836.     vereq(long(a), -1)  # verify PyNumber_Long() copies the sign bit
  1837.  
  1838.     class precfloat(float):
  1839.         __slots__ = ['prec']
  1840.         def __init__(self, value=0.0, prec=12):
  1841.             self.prec = int(prec)
  1842.             float.__init__(value)
  1843.         def __repr__(self):
  1844.             return "%.*g" % (self.prec, self)
  1845.     vereq(repr(precfloat(1.1)), "1.1")
  1846.     a = precfloat(12345)
  1847.     vereq(a, 12345.0)
  1848.     vereq(float(a), 12345.0)
  1849.     verify(float(a).__class__ is float)
  1850.     vereq(hash(a), hash(12345.0))
  1851.     verify((+a).__class__ is float)
  1852.  
  1853.     class madcomplex(complex):
  1854.         def __repr__(self):
  1855.             return "%.17gj%+.17g" % (self.imag, self.real)
  1856.     a = madcomplex(-3, 4)
  1857.     vereq(repr(a), "4j-3")
  1858.     base = complex(-3, 4)
  1859.     veris(base.__class__, complex)
  1860.     vereq(a, base)
  1861.     vereq(complex(a), base)
  1862.     veris(complex(a).__class__, complex)
  1863.     a = madcomplex(a)  # just trying another form of the constructor
  1864.     vereq(repr(a), "4j-3")
  1865.     vereq(a, base)
  1866.     vereq(complex(a), base)
  1867.     veris(complex(a).__class__, complex)
  1868.     vereq(hash(a), hash(base))
  1869.     veris((+a).__class__, complex)
  1870.     veris((a + 0).__class__, complex)
  1871.     vereq(a + 0, base)
  1872.     veris((a - 0).__class__, complex)
  1873.     vereq(a - 0, base)
  1874.     veris((a * 1).__class__, complex)
  1875.     vereq(a * 1, base)
  1876.     veris((a / 1).__class__, complex)
  1877.     vereq(a / 1, base)
  1878.  
  1879.     class madtuple(tuple):
  1880.         _rev = None
  1881.         def rev(self):
  1882.             if self._rev is not None:
  1883.                 return self._rev
  1884.             L = list(self)
  1885.             L.reverse()
  1886.             self._rev = self.__class__(L)
  1887.             return self._rev
  1888.     a = madtuple((1,2,3,4,5,6,7,8,9,0))
  1889.     vereq(a, (1,2,3,4,5,6,7,8,9,0))
  1890.     vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
  1891.     vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
  1892.     for i in range(512):
  1893.         t = madtuple(range(i))
  1894.         u = t.rev()
  1895.         v = u.rev()
  1896.         vereq(v, t)
  1897.     a = madtuple((1,2,3,4,5))
  1898.     vereq(tuple(a), (1,2,3,4,5))
  1899.     verify(tuple(a).__class__ is tuple)
  1900.     vereq(hash(a), hash((1,2,3,4,5)))
  1901.     verify(a[:].__class__ is tuple)
  1902.     verify((a * 1).__class__ is tuple)
  1903.     verify((a * 0).__class__ is tuple)
  1904.     verify((a + ()).__class__ is tuple)
  1905.     a = madtuple(())
  1906.     vereq(tuple(a), ())
  1907.     verify(tuple(a).__class__ is tuple)
  1908.     verify((a + a).__class__ is tuple)
  1909.     verify((a * 0).__class__ is tuple)
  1910.     verify((a * 1).__class__ is tuple)
  1911.     verify((a * 2).__class__ is tuple)
  1912.     verify(a[:].__class__ is tuple)
  1913.  
  1914.     class madstring(str):
  1915.         _rev = None
  1916.         def rev(self):
  1917.             if self._rev is not None:
  1918.                 return self._rev
  1919.             L = list(self)
  1920.             L.reverse()
  1921.             self._rev = self.__class__("".join(L))
  1922.             return self._rev
  1923.     s = madstring("abcdefghijklmnopqrstuvwxyz")
  1924.     vereq(s, "abcdefghijklmnopqrstuvwxyz")
  1925.     vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
  1926.     vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
  1927.     for i in range(256):
  1928.         s = madstring("".join(map(chr, range(i))))
  1929.         t = s.rev()
  1930.         u = t.rev()
  1931.         vereq(u, s)
  1932.     s = madstring("12345")
  1933.     vereq(str(s), "12345")
  1934.     verify(str(s).__class__ is str)
  1935.  
  1936.     base = "\x00" * 5
  1937.     s = madstring(base)
  1938.     vereq(s, base)
  1939.     vereq(str(s), base)
  1940.     verify(str(s).__class__ is str)
  1941.     vereq(hash(s), hash(base))
  1942.     vereq({s: 1}[base], 1)
  1943.     vereq({base: 1}[s], 1)
  1944.     verify((s + "").__class__ is str)
  1945.     vereq(s + "", base)
  1946.     verify(("" + s).__class__ is str)
  1947.     vereq("" + s, base)
  1948.     verify((s * 0).__class__ is str)
  1949.     vereq(s * 0, "")
  1950.     verify((s * 1).__class__ is str)
  1951.     vereq(s * 1, base)
  1952.     verify((s * 2).__class__ is str)
  1953.     vereq(s * 2, base + base)
  1954.     verify(s[:].__class__ is str)
  1955.     vereq(s[:], base)
  1956.     verify(s[0:0].__class__ is str)
  1957.     vereq(s[0:0], "")
  1958.     verify(s.strip().__class__ is str)
  1959.     vereq(s.strip(), base)
  1960.     verify(s.lstrip().__class__ is str)
  1961.     vereq(s.lstrip(), base)
  1962.     verify(s.rstrip().__class__ is str)
  1963.     vereq(s.rstrip(), base)
  1964.     identitytab = ''.join([chr(i) for i in range(256)])
  1965.     verify(s.translate(identitytab).__class__ is str)
  1966.     vereq(s.translate(identitytab), base)
  1967.     verify(s.translate(identitytab, "x").__class__ is str)
  1968.     vereq(s.translate(identitytab, "x"), base)
  1969.     vereq(s.translate(identitytab, "\x00"), "")
  1970.     verify(s.replace("x", "x").__class__ is str)
  1971.     vereq(s.replace("x", "x"), base)
  1972.     verify(s.ljust(len(s)).__class__ is str)
  1973.     vereq(s.ljust(len(s)), base)
  1974.     verify(s.rjust(len(s)).__class__ is str)
  1975.     vereq(s.rjust(len(s)), base)
  1976.     verify(s.center(len(s)).__class__ is str)
  1977.     vereq(s.center(len(s)), base)
  1978.     verify(s.lower().__class__ is str)
  1979.     vereq(s.lower(), base)
  1980.  
  1981.     s = madstring("x y")
  1982.     vereq(s, "x y")
  1983.     verify(intern(s).__class__ is str)
  1984.     verify(intern(s) is intern("x y"))
  1985.     vereq(intern(s), "x y")
  1986.  
  1987.     i = intern("y x")
  1988.     s = madstring("y x")
  1989.     vereq(s, i)
  1990.     verify(intern(s).__class__ is str)
  1991.     verify(intern(s) is i)
  1992.  
  1993.     s = madstring(i)
  1994.     verify(intern(s).__class__ is str)
  1995.     verify(intern(s) is i)
  1996.  
  1997.     class madunicode(unicode):
  1998.         _rev = None
  1999.         def rev(self):
  2000.             if self._rev is not None:
  2001.                 return self._rev
  2002.             L = list(self)
  2003.             L.reverse()
  2004.             self._rev = self.__class__(u"".join(L))
  2005.             return self._rev
  2006.     u = madunicode("ABCDEF")
  2007.     vereq(u, u"ABCDEF")
  2008.     vereq(u.rev(), madunicode(u"FEDCBA"))
  2009.     vereq(u.rev().rev(), madunicode(u"ABCDEF"))
  2010.     base = u"12345"
  2011.     u = madunicode(base)
  2012.     vereq(unicode(u), base)
  2013.     verify(unicode(u).__class__ is unicode)
  2014.     vereq(hash(u), hash(base))
  2015.     vereq({u: 1}[base], 1)
  2016.     vereq({base: 1}[u], 1)
  2017.     verify(u.strip().__class__ is unicode)
  2018.     vereq(u.strip(), base)
  2019.     verify(u.lstrip().__class__ is unicode)
  2020.     vereq(u.lstrip(), base)
  2021.     verify(u.rstrip().__class__ is unicode)
  2022.     vereq(u.rstrip(), base)
  2023.     verify(u.replace(u"x", u"x").__class__ is unicode)
  2024.     vereq(u.replace(u"x", u"x"), base)
  2025.     verify(u.replace(u"xy", u"xy").__class__ is unicode)
  2026.     vereq(u.replace(u"xy", u"xy"), base)
  2027.     verify(u.center(len(u)).__class__ is unicode)
  2028.     vereq(u.center(len(u)), base)
  2029.     verify(u.ljust(len(u)).__class__ is unicode)
  2030.     vereq(u.ljust(len(u)), base)
  2031.     verify(u.rjust(len(u)).__class__ is unicode)
  2032.     vereq(u.rjust(len(u)), base)
  2033.     verify(u.lower().__class__ is unicode)
  2034.     vereq(u.lower(), base)
  2035.     verify(u.upper().__class__ is unicode)
  2036.     vereq(u.upper(), base)
  2037.     verify(u.capitalize().__class__ is unicode)
  2038.     vereq(u.capitalize(), base)
  2039.     verify(u.title().__class__ is unicode)
  2040.     vereq(u.title(), base)
  2041.     verify((u + u"").__class__ is unicode)
  2042.     vereq(u + u"", base)
  2043.     verify((u"" + u).__class__ is unicode)
  2044.     vereq(u"" + u, base)
  2045.     verify((u * 0).__class__ is unicode)
  2046.     vereq(u * 0, u"")
  2047.     verify((u * 1).__class__ is unicode)
  2048.     vereq(u * 1, base)
  2049.     verify((u * 2).__class__ is unicode)
  2050.     vereq(u * 2, base + base)
  2051.     verify(u[:].__class__ is unicode)
  2052.     vereq(u[:], base)
  2053.     verify(u[0:0].__class__ is unicode)
  2054.     vereq(u[0:0], u"")
  2055.  
  2056.     class sublist(list):
  2057.         pass
  2058.     a = sublist(range(5))
  2059.     vereq(a, range(5))
  2060.     a.append("hello")
  2061.     vereq(a, range(5) + ["hello"])
  2062.     a[5] = 5
  2063.     vereq(a, range(6))
  2064.     a.extend(range(6, 20))
  2065.     vereq(a, range(20))
  2066.     a[-5:] = []
  2067.     vereq(a, range(15))
  2068.     del a[10:15]
  2069.     vereq(len(a), 10)
  2070.     vereq(a, range(10))
  2071.     vereq(list(a), range(10))
  2072.     vereq(a[0], 0)
  2073.     vereq(a[9], 9)
  2074.     vereq(a[-10], 0)
  2075.     vereq(a[-1], 9)
  2076.     vereq(a[:5], range(5))
  2077.  
  2078.     class CountedInput(file):
  2079.         """Counts lines read by self.readline().
  2080.  
  2081.         self.lineno is the 0-based ordinal of the last line read, up to
  2082.         a maximum of one greater than the number of lines in the file.
  2083.  
  2084.         self.ateof is true if and only if the final "" line has been read,
  2085.         at which point self.lineno stops incrementing, and further calls
  2086.         to readline() continue to return "".
  2087.         """
  2088.  
  2089.         lineno = 0
  2090.         ateof = 0
  2091.         def readline(self):
  2092.             if self.ateof:
  2093.                 return ""
  2094.             s = file.readline(self)
  2095.             # Next line works too.
  2096.             # s = super(CountedInput, self).readline()
  2097.             self.lineno += 1
  2098.             if s == "":
  2099.                 self.ateof = 1
  2100.             return s
  2101.  
  2102.     f = file(name=TESTFN, mode='w')
  2103.     lines = ['a\n', 'b\n', 'c\n']
  2104.     try:
  2105.         f.writelines(lines)
  2106.         f.close()
  2107.         f = CountedInput(TESTFN)
  2108.         for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
  2109.             got = f.readline()
  2110.             vereq(expected, got)
  2111.             vereq(f.lineno, i)
  2112.             vereq(f.ateof, (i > len(lines)))
  2113.         f.close()
  2114.     finally:
  2115.         try:
  2116.             f.close()
  2117.         except:
  2118.             pass
  2119.         try:
  2120.             import os
  2121.             os.unlink(TESTFN)
  2122.         except:
  2123.             pass
  2124.  
  2125. def keywords():
  2126.     if verbose:
  2127.         print "Testing keyword args to basic type constructors ..."
  2128.     vereq(int(x=1), 1)
  2129.     vereq(float(x=2), 2.0)
  2130.     vereq(long(x=3), 3L)
  2131.     vereq(complex(imag=42, real=666), complex(666, 42))
  2132.     vereq(str(object=500), '500')
  2133.     vereq(unicode(string='abc', errors='strict'), u'abc')
  2134.     vereq(tuple(sequence=range(3)), (0, 1, 2))
  2135.     vereq(list(sequence=(0, 1, 2)), range(3))
  2136.     vereq(dict(items={1: 2}), {1: 2})
  2137.  
  2138.     for constructor in (int, float, long, complex, str, unicode,
  2139.                         tuple, list, dict, file):
  2140.         try:
  2141.             constructor(bogus_keyword_arg=1)
  2142.         except TypeError:
  2143.             pass
  2144.         else:
  2145.             raise TestFailed("expected TypeError from bogus keyword "
  2146.                              "argument to %r" % constructor)
  2147.  
  2148. def restricted():
  2149.     import rexec
  2150.     if verbose:
  2151.         print "Testing interaction with restricted execution ..."
  2152.  
  2153.     sandbox = rexec.RExec()
  2154.  
  2155.     code1 = """f = open(%r, 'w')""" % TESTFN
  2156.     code2 = """f = file(%r, 'w')""" % TESTFN
  2157.     code3 = """\
  2158. f = open(%r)
  2159. t = type(f)  # a sneaky way to get the file() constructor
  2160. f.close()
  2161. f = t(%r, 'w')  # rexec can't catch this by itself
  2162. """ % (TESTFN, TESTFN)
  2163.  
  2164.     f = open(TESTFN, 'w')  # Create the file so code3 can find it.
  2165.     f.close()
  2166.  
  2167.     try:
  2168.         for code in code1, code2, code3:
  2169.             try:
  2170.                 sandbox.r_exec(code)
  2171.             except IOError, msg:
  2172.                 if str(msg).find("restricted") >= 0:
  2173.                     outcome = "OK"
  2174.                 else:
  2175.                     outcome = "got an exception, but not an expected one"
  2176.             else:
  2177.                 outcome = "expected a restricted-execution exception"
  2178.  
  2179.             if outcome != "OK":
  2180.                 raise TestFailed("%s, in %r" % (outcome, code))
  2181.  
  2182.     finally:
  2183.         try:
  2184.             import os
  2185.             os.unlink(TESTFN)
  2186.         except:
  2187.             pass
  2188.  
  2189. def str_subclass_as_dict_key():
  2190.     if verbose:
  2191.         print "Testing a str subclass used as dict key .."
  2192.  
  2193.     class cistr(str):
  2194.         """Sublcass of str that computes __eq__ case-insensitively.
  2195.  
  2196.         Also computes a hash code of the string in canonical form.
  2197.         """
  2198.  
  2199.         def __init__(self, value):
  2200.             self.canonical = value.lower()
  2201.             self.hashcode = hash(self.canonical)
  2202.  
  2203.         def __eq__(self, other):
  2204.             if not isinstance(other, cistr):
  2205.                 other = cistr(other)
  2206.             return self.canonical == other.canonical
  2207.  
  2208.         def __hash__(self):
  2209.             return self.hashcode
  2210.  
  2211.     vereq(cistr('ABC'), 'abc')
  2212.     vereq('aBc', cistr('ABC'))
  2213.     vereq(str(cistr('ABC')), 'ABC')
  2214.  
  2215.     d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
  2216.     vereq(d[cistr('one')], 1)
  2217.     vereq(d[cistr('tWo')], 2)
  2218.     vereq(d[cistr('THrEE')], 3)
  2219.     verify(cistr('ONe') in d)
  2220.     vereq(d.get(cistr('thrEE')), 3)
  2221.  
  2222. def classic_comparisons():
  2223.     if verbose: print "Testing classic comparisons..."
  2224.     class classic:
  2225.         pass
  2226.     for base in (classic, int, object):
  2227.         if verbose: print "        (base = %s)" % base
  2228.         class C(base):
  2229.             def __init__(self, value):
  2230.                 self.value = int(value)
  2231.             def __cmp__(self, other):
  2232.                 if isinstance(other, C):
  2233.                     return cmp(self.value, other.value)
  2234.                 if isinstance(other, int) or isinstance(other, long):
  2235.                     return cmp(self.value, other)
  2236.                 return NotImplemented
  2237.         c1 = C(1)
  2238.         c2 = C(2)
  2239.         c3 = C(3)
  2240.         vereq(c1, 1)
  2241.         c = {1: c1, 2: c2, 3: c3}
  2242.         for x in 1, 2, 3:
  2243.             for y in 1, 2, 3:
  2244.                 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
  2245.                 for op in "<", "<=", "==", "!=", ">", ">=":
  2246.                     verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
  2247.                            "x=%d, y=%d" % (x, y))
  2248.                 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
  2249.                 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
  2250.  
  2251. def rich_comparisons():
  2252.     if verbose:
  2253.         print "Testing rich comparisons..."
  2254.     class Z(complex):
  2255.         pass
  2256.     z = Z(1)
  2257.     vereq(z, 1+0j)
  2258.     vereq(1+0j, z)
  2259.     class ZZ(complex):
  2260.         def __eq__(self, other):
  2261.             try:
  2262.                 return abs(self - other) <= 1e-6
  2263.             except:
  2264.                 return NotImplemented
  2265.     zz = ZZ(1.0000003)
  2266.     vereq(zz, 1+0j)
  2267.     vereq(1+0j, zz)
  2268.  
  2269.     class classic:
  2270.         pass
  2271.     for base in (classic, int, object, list):
  2272.         if verbose: print "        (base = %s)" % base
  2273.         class C(base):
  2274.             def __init__(self, value):
  2275.                 self.value = int(value)
  2276.             def __cmp__(self, other):
  2277.                 raise TestFailed, "shouldn't call __cmp__"
  2278.             def __eq__(self, other):
  2279.                 if isinstance(other, C):
  2280.                     return self.value == other.value
  2281.                 if isinstance(other, int) or isinstance(other, long):
  2282.                     return self.value == other
  2283.                 return NotImplemented
  2284.             def __ne__(self, other):
  2285.                 if isinstance(other, C):
  2286.                     return self.value != other.value
  2287.                 if isinstance(other, int) or isinstance(other, long):
  2288.                     return self.value != other
  2289.                 return NotImplemented
  2290.             def __lt__(self, other):
  2291.                 if isinstance(other, C):
  2292.                     return self.value < other.value
  2293.                 if isinstance(other, int) or isinstance(other, long):
  2294.                     return self.value < other
  2295.                 return NotImplemented
  2296.             def __le__(self, other):
  2297.                 if isinstance(other, C):
  2298.                     return self.value <= other.value
  2299.                 if isinstance(other, int) or isinstance(other, long):
  2300.                     return self.value <= other
  2301.                 return NotImplemented
  2302.             def __gt__(self, other):
  2303.                 if isinstance(other, C):
  2304.                     return self.value > other.value
  2305.                 if isinstance(other, int) or isinstance(other, long):
  2306.                     return self.value > other
  2307.                 return NotImplemented
  2308.             def __ge__(self, other):
  2309.                 if isinstance(other, C):
  2310.                     return self.value >= other.value
  2311.                 if isinstance(other, int) or isinstance(other, long):
  2312.                     return self.value >= other
  2313.                 return NotImplemented
  2314.         c1 = C(1)
  2315.         c2 = C(2)
  2316.         c3 = C(3)
  2317.         vereq(c1, 1)
  2318.         c = {1: c1, 2: c2, 3: c3}
  2319.         for x in 1, 2, 3:
  2320.             for y in 1, 2, 3:
  2321.                 for op in "<", "<=", "==", "!=", ">", ">=":
  2322.                     verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
  2323.                            "x=%d, y=%d" % (x, y))
  2324.                     verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
  2325.                            "x=%d, y=%d" % (x, y))
  2326.                     verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
  2327.                            "x=%d, y=%d" % (x, y))
  2328.  
  2329. def coercions():
  2330.     if verbose: print "Testing coercions..."
  2331.     class I(int): pass
  2332.     coerce(I(0), 0)
  2333.     coerce(0, I(0))
  2334.     class L(long): pass
  2335.     coerce(L(0), 0)
  2336.     coerce(L(0), 0L)
  2337.     coerce(0, L(0))
  2338.     coerce(0L, L(0))
  2339.     class F(float): pass
  2340.     coerce(F(0), 0)
  2341.     coerce(F(0), 0L)
  2342.     coerce(F(0), 0.)
  2343.     coerce(0, F(0))
  2344.     coerce(0L, F(0))
  2345.     coerce(0., F(0))
  2346.     class C(complex): pass
  2347.     coerce(C(0), 0)
  2348.     coerce(C(0), 0L)
  2349.     coerce(C(0), 0.)
  2350.     coerce(C(0), 0j)
  2351.     coerce(0, C(0))
  2352.     coerce(0L, C(0))
  2353.     coerce(0., C(0))
  2354.     coerce(0j, C(0))
  2355.  
  2356. def descrdoc():
  2357.     if verbose: print "Testing descriptor doc strings..."
  2358.     def check(descr, what):
  2359.         vereq(descr.__doc__, what)
  2360.     check(file.closed, "flag set if the file is closed") # getset descriptor
  2361.     check(file.name, "file name") # member descriptor
  2362.  
  2363. def setclass():
  2364.     if verbose: print "Testing __class__ assignment..."
  2365.     class C(object): pass
  2366.     class D(object): pass
  2367.     class E(object): pass
  2368.     class F(D, E): pass
  2369.     for cls in C, D, E, F:
  2370.         for cls2 in C, D, E, F:
  2371.             x = cls()
  2372.             x.__class__ = cls2
  2373.             verify(x.__class__ is cls2)
  2374.             x.__class__ = cls
  2375.             verify(x.__class__ is cls)
  2376.     def cant(x, C):
  2377.         try:
  2378.             x.__class__ = C
  2379.         except TypeError:
  2380.             pass
  2381.         else:
  2382.             raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
  2383.         try:
  2384.             delattr(x, "__class__")
  2385.         except TypeError:
  2386.             pass
  2387.         else:
  2388.             raise TestFailed, "shouldn't allow del %r.__class__" % x
  2389.     cant(C(), list)
  2390.     cant(list(), C)
  2391.     cant(C(), 1)
  2392.     cant(C(), object)
  2393.     cant(object(), list)
  2394.     cant(list(), object)
  2395.  
  2396. def setdict():
  2397.     if verbose: print "Testing __dict__ assignment..."
  2398.     class C(object): pass
  2399.     a = C()
  2400.     a.__dict__ = {'b': 1}
  2401.     vereq(a.b, 1)
  2402.     def cant(x, dict):
  2403.         try:
  2404.             x.__dict__ = dict
  2405.         except TypeError:
  2406.             pass
  2407.         else:
  2408.             raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
  2409.     cant(a, None)
  2410.     cant(a, [])
  2411.     cant(a, 1)
  2412.     del a.__dict__ # Deleting __dict__ is allowed
  2413.     # Classes don't allow __dict__ assignment
  2414.     cant(C, {})
  2415.  
  2416. def pickles():
  2417.     if verbose:
  2418.         print "Testing pickling and copying new-style classes and objects..."
  2419.     import pickle, cPickle
  2420.  
  2421.     def sorteditems(d):
  2422.         L = d.items()
  2423.         L.sort()
  2424.         return L
  2425.  
  2426.     global C
  2427.     class C(object):
  2428.         def __init__(self, a, b):
  2429.             super(C, self).__init__()
  2430.             self.a = a
  2431.             self.b = b
  2432.         def __repr__(self):
  2433.             return "C(%r, %r)" % (self.a, self.b)
  2434.  
  2435.     global C1
  2436.     class C1(list):
  2437.         def __new__(cls, a, b):
  2438.             return super(C1, cls).__new__(cls)
  2439.         def __init__(self, a, b):
  2440.             self.a = a
  2441.             self.b = b
  2442.         def __repr__(self):
  2443.             return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
  2444.  
  2445.     global C2
  2446.     class C2(int):
  2447.         def __new__(cls, a, b, val=0):
  2448.             return super(C2, cls).__new__(cls, val)
  2449.         def __init__(self, a, b, val=0):
  2450.             self.a = a
  2451.             self.b = b
  2452.         def __repr__(self):
  2453.             return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
  2454.  
  2455.     global C3
  2456.     class C3(object):
  2457.         def __init__(self, foo):
  2458.             self.foo = foo
  2459.         def __getstate__(self):
  2460.             return self.foo
  2461.         def __setstate__(self, foo):
  2462.             self.foo = foo
  2463.  
  2464.     global C4classic, C4
  2465.     class C4classic: # classic
  2466.         pass
  2467.     class C4(C4classic, object): # mixed inheritance
  2468.         pass
  2469.  
  2470.     for p in pickle, cPickle:
  2471.         for bin in 0, 1:
  2472.             if verbose:
  2473.                 print p.__name__, ["text", "binary"][bin]
  2474.  
  2475.             for cls in C, C1, C2:
  2476.                 s = p.dumps(cls, bin)
  2477.                 cls2 = p.loads(s)
  2478.                 verify(cls2 is cls)
  2479.  
  2480.             a = C1(1, 2); a.append(42); a.append(24)
  2481.             b = C2("hello", "world", 42)
  2482.             s = p.dumps((a, b), bin)
  2483.             x, y = p.loads(s)
  2484.             vereq(x.__class__, a.__class__)
  2485.             vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
  2486.             vereq(y.__class__, b.__class__)
  2487.             vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
  2488.             vereq(`x`, `a`)
  2489.             vereq(`y`, `b`)
  2490.             if verbose:
  2491.                 print "a = x =", a
  2492.                 print "b = y =", b
  2493.             # Test for __getstate__ and __setstate__ on new style class
  2494.             u = C3(42)
  2495.             s = p.dumps(u, bin)
  2496.             v = p.loads(s)
  2497.             veris(u.__class__, v.__class__)
  2498.             vereq(u.foo, v.foo)
  2499.             # Test for picklability of hybrid class
  2500.             u = C4()
  2501.             u.foo = 42
  2502.             s = p.dumps(u, bin)
  2503.             v = p.loads(s)
  2504.             veris(u.__class__, v.__class__)
  2505.             vereq(u.foo, v.foo)
  2506.  
  2507.     # Testing copy.deepcopy()
  2508.     if verbose:
  2509.         print "deepcopy"
  2510.     import copy
  2511.     for cls in C, C1, C2:
  2512.         cls2 = copy.deepcopy(cls)
  2513.         verify(cls2 is cls)
  2514.  
  2515.     a = C1(1, 2); a.append(42); a.append(24)
  2516.     b = C2("hello", "world", 42)
  2517.     x, y = copy.deepcopy((a, b))
  2518.     vereq(x.__class__, a.__class__)
  2519.     vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
  2520.     vereq(y.__class__, b.__class__)
  2521.     vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
  2522.     vereq(`x`, `a`)
  2523.     vereq(`y`, `b`)
  2524.     if verbose:
  2525.         print "a = x =", a
  2526.         print "b = y =", b
  2527.  
  2528. def pickleslots():
  2529.     if verbose: print "Testing pickling of classes with __slots__ ..."
  2530.     import pickle, cPickle
  2531.     # Pickling of classes with __slots__ but without __getstate__ should fail
  2532.     global B, C, D, E
  2533.     class B(object):
  2534.         pass
  2535.     for base in [object, B]:
  2536.         class C(base):
  2537.             __slots__ = ['a']
  2538.         class D(C):
  2539.             pass
  2540.         try:
  2541.             pickle.dumps(C())
  2542.         except TypeError:
  2543.             pass
  2544.         else:
  2545.             raise TestFailed, "should fail: pickle C instance - %s" % base
  2546.         try:
  2547.             cPickle.dumps(C())
  2548.         except TypeError:
  2549.             pass
  2550.         else:
  2551.             raise TestFailed, "should fail: cPickle C instance - %s" % base
  2552.         try:
  2553.             pickle.dumps(C())
  2554.         except TypeError:
  2555.             pass
  2556.         else:
  2557.             raise TestFailed, "should fail: pickle D instance - %s" % base
  2558.         try:
  2559.             cPickle.dumps(D())
  2560.         except TypeError:
  2561.             pass
  2562.         else:
  2563.             raise TestFailed, "should fail: cPickle D instance - %s" % base
  2564.         # Give C a __getstate__ and __setstate__
  2565.         class C(base):
  2566.             __slots__ = ['a']
  2567.             def __getstate__(self):
  2568.                 try:
  2569.                     d = self.__dict__.copy()
  2570.                 except AttributeError:
  2571.                     d = {}
  2572.                 try:
  2573.                     d['a'] = self.a
  2574.                 except AttributeError:
  2575.                     pass
  2576.                 return d
  2577.             def __setstate__(self, d):
  2578.                 for k, v in d.items():
  2579.                     setattr(self, k, v)
  2580.         class D(C):
  2581.             pass
  2582.         # Now it should work
  2583.         x = C()
  2584.         y = pickle.loads(pickle.dumps(x))
  2585.         vereq(hasattr(y, 'a'), 0)
  2586.         y = cPickle.loads(cPickle.dumps(x))
  2587.         vereq(hasattr(y, 'a'), 0)
  2588.         x.a = 42
  2589.         y = pickle.loads(pickle.dumps(x))
  2590.         vereq(y.a, 42)
  2591.         y = cPickle.loads(cPickle.dumps(x))
  2592.         vereq(y.a, 42)
  2593.         x = D()
  2594.         x.a = 42
  2595.         x.b = 100
  2596.         y = pickle.loads(pickle.dumps(x))
  2597.         vereq(y.a + y.b, 142)
  2598.         y = cPickle.loads(cPickle.dumps(x))
  2599.         vereq(y.a + y.b, 142)
  2600.         # But a subclass that adds a slot should not work
  2601.         class E(C):
  2602.             __slots__ = ['b']
  2603.         try:
  2604.             pickle.dumps(E())
  2605.         except TypeError:
  2606.             pass
  2607.         else:
  2608.             raise TestFailed, "should fail: pickle E instance - %s" % base
  2609.         try:
  2610.             cPickle.dumps(E())
  2611.         except TypeError:
  2612.             pass
  2613.         else:
  2614.             raise TestFailed, "should fail: cPickle E instance - %s" % base
  2615.  
  2616. def copies():
  2617.     if verbose: print "Testing copy.copy() and copy.deepcopy()..."
  2618.     import copy
  2619.     class C(object):
  2620.         pass
  2621.  
  2622.     a = C()
  2623.     a.foo = 12
  2624.     b = copy.copy(a)
  2625.     vereq(b.__dict__, a.__dict__)
  2626.  
  2627.     a.bar = [1,2,3]
  2628.     c = copy.copy(a)
  2629.     vereq(c.bar, a.bar)
  2630.     verify(c.bar is a.bar)
  2631.  
  2632.     d = copy.deepcopy(a)
  2633.     vereq(d.__dict__, a.__dict__)
  2634.     a.bar.append(4)
  2635.     vereq(d.bar, [1,2,3])
  2636.  
  2637. def binopoverride():
  2638.     if verbose: print "Testing overrides of binary operations..."
  2639.     class I(int):
  2640.         def __repr__(self):
  2641.             return "I(%r)" % int(self)
  2642.         def __add__(self, other):
  2643.             return I(int(self) + int(other))
  2644.         __radd__ = __add__
  2645.         def __pow__(self, other, mod=None):
  2646.             if mod is None:
  2647.                 return I(pow(int(self), int(other)))
  2648.             else:
  2649.                 return I(pow(int(self), int(other), int(mod)))
  2650.         def __rpow__(self, other, mod=None):
  2651.             if mod is None:
  2652.                 return I(pow(int(other), int(self), mod))
  2653.             else:
  2654.                 return I(pow(int(other), int(self), int(mod)))
  2655.  
  2656.     vereq(`I(1) + I(2)`, "I(3)")
  2657.     vereq(`I(1) + 2`, "I(3)")
  2658.     vereq(`1 + I(2)`, "I(3)")
  2659.     vereq(`I(2) ** I(3)`, "I(8)")
  2660.     vereq(`2 ** I(3)`, "I(8)")
  2661.     vereq(`I(2) ** 3`, "I(8)")
  2662.     vereq(`pow(I(2), I(3), I(5))`, "I(3)")
  2663.     class S(str):
  2664.         def __eq__(self, other):
  2665.             return self.lower() == other.lower()
  2666.  
  2667. def subclasspropagation():
  2668.     if verbose: print "Testing propagation of slot functions to subclasses..."
  2669.     class A(object):
  2670.         pass
  2671.     class B(A):
  2672.         pass
  2673.     class C(A):
  2674.         pass
  2675.     class D(B, C):
  2676.         pass
  2677.     d = D()
  2678.     vereq(hash(d), id(d))
  2679.     A.__hash__ = lambda self: 42
  2680.     vereq(hash(d), 42)
  2681.     C.__hash__ = lambda self: 314
  2682.     vereq(hash(d), 314)
  2683.     B.__hash__ = lambda self: 144
  2684.     vereq(hash(d), 144)
  2685.     D.__hash__ = lambda self: 100
  2686.     vereq(hash(d), 100)
  2687.     del D.__hash__
  2688.     vereq(hash(d), 144)
  2689.     del B.__hash__
  2690.     vereq(hash(d), 314)
  2691.     del C.__hash__
  2692.     vereq(hash(d), 42)
  2693.     del A.__hash__
  2694.     vereq(hash(d), id(d))
  2695.     d.foo = 42
  2696.     d.bar = 42
  2697.     vereq(d.foo, 42)
  2698.     vereq(d.bar, 42)
  2699.     def __getattribute__(self, name):
  2700.         if name == "foo":
  2701.             return 24
  2702.         return object.__getattribute__(self, name)
  2703.     A.__getattribute__ = __getattribute__
  2704.     vereq(d.foo, 24)
  2705.     vereq(d.bar, 42)
  2706.     def __getattr__(self, name):
  2707.         if name in ("spam", "foo", "bar"):
  2708.             return "hello"
  2709.         raise AttributeError, name
  2710.     B.__getattr__ = __getattr__
  2711.     vereq(d.spam, "hello")
  2712.     vereq(d.foo, 24)
  2713.     vereq(d.bar, 42)
  2714.     del A.__getattribute__
  2715.     vereq(d.foo, 42)
  2716.     del d.foo
  2717.     vereq(d.foo, "hello")
  2718.     vereq(d.bar, 42)
  2719.     del B.__getattr__
  2720.     try:
  2721.         d.foo
  2722.     except AttributeError:
  2723.         pass
  2724.     else:
  2725.         raise TestFailed, "d.foo should be undefined now"
  2726.  
  2727.     # Test a nasty bug in recurse_down_subclasses()
  2728.     import gc
  2729.     class A(object):
  2730.         pass
  2731.     class B(A):
  2732.         pass
  2733.     del B
  2734.     gc.collect()
  2735.     A.__setitem__ = lambda *a: None # crash
  2736.  
  2737. def buffer_inherit():
  2738.     import binascii
  2739.     # SF bug [#470040] ParseTuple t# vs subclasses.
  2740.     if verbose:
  2741.         print "Testing that buffer interface is inherited ..."
  2742.  
  2743.     class MyStr(str):
  2744.         pass
  2745.     base = 'abc'
  2746.     m = MyStr(base)
  2747.     # b2a_hex uses the buffer interface to get its argument's value, via
  2748.     # PyArg_ParseTuple 't#' code.
  2749.     vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
  2750.  
  2751.     # It's not clear that unicode will continue to support the character
  2752.     # buffer interface, and this test will fail if that's taken away.
  2753.     class MyUni(unicode):
  2754.         pass
  2755.     base = u'abc'
  2756.     m = MyUni(base)
  2757.     vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
  2758.  
  2759.     class MyInt(int):
  2760.         pass
  2761.     m = MyInt(42)
  2762.     try:
  2763.         binascii.b2a_hex(m)
  2764.         raise TestFailed('subclass of int should not have a buffer interface')
  2765.     except TypeError:
  2766.         pass
  2767.  
  2768. def str_of_str_subclass():
  2769.     import binascii
  2770.     import cStringIO
  2771.  
  2772.     if verbose:
  2773.         print "Testing __str__ defined in subclass of str ..."
  2774.  
  2775.     class octetstring(str):
  2776.         def __str__(self):
  2777.             return binascii.b2a_hex(self)
  2778.         def __repr__(self):
  2779.             return self + " repr"
  2780.  
  2781.     o = octetstring('A')
  2782.     vereq(type(o), octetstring)
  2783.     vereq(type(str(o)), str)
  2784.     vereq(type(repr(o)), str)
  2785.     vereq(ord(o), 0x41)
  2786.     vereq(str(o), '41')
  2787.     vereq(repr(o), 'A repr')
  2788.     vereq(o.__str__(), '41')
  2789.     vereq(o.__repr__(), 'A repr')
  2790.  
  2791.     capture = cStringIO.StringIO()
  2792.     # Calling str() or not exercises different internal paths.
  2793.     print >> capture, o
  2794.     print >> capture, str(o)
  2795.     vereq(capture.getvalue(), '41\n41\n')
  2796.     capture.close()
  2797.  
  2798. def kwdargs():
  2799.     if verbose: print "Testing keyword arguments to __init__, __call__..."
  2800.     def f(a): return a
  2801.     vereq(f.__call__(a=42), 42)
  2802.     a = []
  2803.     list.__init__(a, sequence=[0, 1, 2])
  2804.     vereq(a, [0, 1, 2])
  2805.  
  2806. def delhook():
  2807.     if verbose: print "Testing __del__ hook..."
  2808.     log = []
  2809.     class C(object):
  2810.         def __del__(self):
  2811.             log.append(1)
  2812.     c = C()
  2813.     vereq(log, [])
  2814.     del c
  2815.     vereq(log, [1])
  2816.  
  2817.     class D(object): pass
  2818.     d = D()
  2819.     try: del d[0]
  2820.     except TypeError: pass
  2821.     else: raise TestFailed, "invalid del() didn't raise TypeError"
  2822.  
  2823. def hashinherit():
  2824.     if verbose: print "Testing hash of mutable subclasses..."
  2825.  
  2826.     class mydict(dict):
  2827.         pass
  2828.     d = mydict()
  2829.     try:
  2830.         hash(d)
  2831.     except TypeError:
  2832.         pass
  2833.     else:
  2834.         raise TestFailed, "hash() of dict subclass should fail"
  2835.  
  2836.     class mylist(list):
  2837.         pass
  2838.     d = mylist()
  2839.     try:
  2840.         hash(d)
  2841.     except TypeError:
  2842.         pass
  2843.     else:
  2844.         raise TestFailed, "hash() of list subclass should fail"
  2845.  
  2846. def strops():
  2847.     try: 'a' + 5
  2848.     except TypeError: pass
  2849.     else: raise TestFailed, "'' + 5 doesn't raise TypeError"
  2850.  
  2851.     try: ''.split('')
  2852.     except ValueError: pass
  2853.     else: raise TestFailed, "''.split('') doesn't raise ValueError"
  2854.  
  2855.     try: ''.join([0])
  2856.     except TypeError: pass
  2857.     else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
  2858.  
  2859.     try: ''.rindex('5')
  2860.     except ValueError: pass
  2861.     else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
  2862.  
  2863.     try: ''.replace('', '')
  2864.     except ValueError: pass
  2865.     else: raise TestFailed, "''.replace('', '') doesn't raise ValueError"
  2866.  
  2867.     try: '%(n)s' % None
  2868.     except TypeError: pass
  2869.     else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
  2870.  
  2871.     try: '%(n' % {}
  2872.     except ValueError: pass
  2873.     else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
  2874.  
  2875.     try: '%*s' % ('abc')
  2876.     except TypeError: pass
  2877.     else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
  2878.  
  2879.     try: '%*.*s' % ('abc', 5)
  2880.     except TypeError: pass
  2881.     else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
  2882.  
  2883.     try: '%s' % (1, 2)
  2884.     except TypeError: pass
  2885.     else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
  2886.  
  2887.     try: '%' % None
  2888.     except ValueError: pass
  2889.     else: raise TestFailed, "'%' % None doesn't raise ValueError"
  2890.  
  2891.     vereq('534253'.isdigit(), 1)
  2892.     vereq('534253x'.isdigit(), 0)
  2893.     vereq('%c' % 5, '\x05')
  2894.     vereq('%c' % '5', '5')
  2895.  
  2896. def deepcopyrecursive():
  2897.     if verbose: print "Testing deepcopy of recursive objects..."
  2898.     class Node:
  2899.         pass
  2900.     a = Node()
  2901.     b = Node()
  2902.     a.b = b
  2903.     b.a = a
  2904.     z = deepcopy(a) # This blew up before
  2905.  
  2906. def modules():
  2907.     if verbose: print "Testing uninitialized module objects..."
  2908.     from types import ModuleType as M
  2909.     m = M.__new__(M)
  2910.     str(m)
  2911.     vereq(hasattr(m, "__name__"), 0)
  2912.     vereq(hasattr(m, "__file__"), 0)
  2913.     vereq(hasattr(m, "foo"), 0)
  2914.     vereq(m.__dict__, None)
  2915.     m.foo = 1
  2916.     vereq(m.__dict__, {"foo": 1})
  2917.  
  2918. def docdescriptor():
  2919.     # SF bug 542984
  2920.     if verbose: print "Testing __doc__ descriptor..."
  2921.     class DocDescr(object):
  2922.         def __get__(self, object, otype):
  2923.             if object:
  2924.                 object = object.__class__.__name__ + ' instance'
  2925.             if otype:
  2926.                 otype = otype.__name__
  2927.             return 'object=%s; type=%s' % (object, otype)
  2928.     class OldClass:
  2929.         __doc__ = DocDescr()
  2930.     class NewClass(object):
  2931.         __doc__ = DocDescr()
  2932.     vereq(OldClass.__doc__, 'object=None; type=OldClass')
  2933.     vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
  2934.     vereq(NewClass.__doc__, 'object=None; type=NewClass')
  2935.     vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
  2936.  
  2937. def imulbug():
  2938.     # SF bug 544647
  2939.     if verbose: print "Testing for __imul__ problems..."
  2940.     class C(object):
  2941.         def __imul__(self, other):
  2942.             return (self, other)
  2943.     x = C()
  2944.     y = x
  2945.     y *= 1.0
  2946.     vereq(y, (x, 1.0))
  2947.     y = x
  2948.     y *= 2
  2949.     vereq(y, (x, 2))
  2950.     y = x
  2951.     y *= 3L
  2952.     vereq(y, (x, 3L))
  2953.     y = x
  2954.     y *= 1L<<100
  2955.     vereq(y, (x, 1L<<100))
  2956.     y = x
  2957.     y *= None
  2958.     vereq(y, (x, None))
  2959.     y = x
  2960.     y *= "foo"
  2961.     vereq(y, (x, "foo"))
  2962.  
  2963. def copy_setstate():
  2964.     if verbose:
  2965.         print "Testing that copy.*copy() correctly uses __setstate__..."
  2966.     import copy
  2967.     class C(object):
  2968.         def __init__(self, foo=None):
  2969.             self.foo = foo
  2970.             self.__foo = foo
  2971.         def setfoo(self, foo=None):
  2972.             self.foo = foo
  2973.         def getfoo(self):
  2974.             return self.__foo
  2975.         def __getstate__(self):
  2976.             return [self.foo]
  2977.         def __setstate__(self, lst):
  2978.             assert len(lst) == 1
  2979.             self.__foo = self.foo = lst[0]
  2980.     a = C(42)
  2981.     a.setfoo(24)
  2982.     vereq(a.foo, 24)
  2983.     vereq(a.getfoo(), 42)
  2984.     b = copy.copy(a)
  2985.     vereq(b.foo, 24)
  2986.     vereq(b.getfoo(), 24)
  2987.     b = copy.deepcopy(a)
  2988.     vereq(b.foo, 24)
  2989.     vereq(b.getfoo(), 24)
  2990.  
  2991. def subtype_resurrection():
  2992.     if verbose:
  2993.         print "Testing resurrection of new-style instance..."
  2994.  
  2995.     class C(object):
  2996.         container = []
  2997.  
  2998.         def __del__(self):
  2999.             # resurrect the instance
  3000.             C.container.append(self)
  3001.  
  3002.     c = C()
  3003.     c.attr = 42
  3004.     # The most interesting thing here is whether this blows up, due to flawed
  3005.     #  GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
  3006.     del c
  3007.  
  3008.     # If that didn't blow up, it's also interesting to see whether clearing
  3009.     # the last container slot works:  that will attempt to delete c again,
  3010.     # which will cause c to get appended back to the container again "during"
  3011.     # the del.
  3012.     del C.container[-1]
  3013.     vereq(len(C.container), 1)
  3014.     vereq(C.container[-1].attr, 42)
  3015.  
  3016.     # Make c mortal again, so that the test framework with -l doesn't report
  3017.     # it as a leak.
  3018.     del C.__del__
  3019.  
  3020. def funnynew():
  3021.     if verbose: print "Testing __new__ returning something unexpected..."
  3022.     class C(object):
  3023.         def __new__(cls, arg):
  3024.             if isinstance(arg, str): return [1, 2, 3]
  3025.             elif isinstance(arg, int): return object.__new__(D)
  3026.             else: return object.__new__(cls)
  3027.     class D(C):
  3028.         def __init__(self, arg):
  3029.             self.foo = arg
  3030.     vereq(C("1"), [1, 2, 3])
  3031.     vereq(D("1"), [1, 2, 3])
  3032.     d = D(None)
  3033.     veris(d.foo, None)
  3034.     d = C(1)
  3035.     vereq(isinstance(d, D), True)
  3036.     vereq(d.foo, 1)
  3037.     d = D(1)
  3038.     vereq(isinstance(d, D), True)
  3039.     vereq(d.foo, 1)
  3040.  
  3041. def test_main():
  3042.     class_docstrings()
  3043.     lists()
  3044.     dicts()
  3045.     dict_constructor()
  3046.     test_dir()
  3047.     ints()
  3048.     longs()
  3049.     floats()
  3050.     complexes()
  3051.     spamlists()
  3052.     spamdicts()
  3053.     pydicts()
  3054.     pylists()
  3055.     metaclass()
  3056.     pymods()
  3057.     multi()
  3058.     diamond()
  3059.     objects()
  3060.     slots()
  3061.     dynamics()
  3062.     errors()
  3063.     classmethods()
  3064.     staticmethods()
  3065.     classic()
  3066.     compattr()
  3067.     newslot()
  3068.     altmro()
  3069.     overloading()
  3070.     methods()
  3071.     specials()
  3072.     weakrefs()
  3073.     properties()
  3074.     supers()
  3075.     inherits()
  3076.     keywords()
  3077.     restricted()
  3078.     str_subclass_as_dict_key()
  3079.     classic_comparisons()
  3080.     rich_comparisons()
  3081.     coercions()
  3082.     descrdoc()
  3083.     setclass()
  3084.     setdict()
  3085.     pickles()
  3086.     copies()
  3087.     binopoverride()
  3088.     subclasspropagation()
  3089.     buffer_inherit()
  3090.     str_of_str_subclass()
  3091.     kwdargs()
  3092.     delhook()
  3093.     hashinherit()
  3094.     strops()
  3095.     deepcopyrecursive()
  3096.     modules()
  3097.     pickleslots()
  3098.     docdescriptor()
  3099.     imulbug()
  3100.     copy_setstate()
  3101.     subtype_resurrection()
  3102.     funnynew()
  3103.     if verbose: print "All OK"
  3104.  
  3105. if __name__ == "__main__":
  3106.     test_main()
  3107.